Example #1
0
/*  Load the list from a file
 
 param:  heap    pointer to the list
 param:  filePtr	pointer to the file
 pre:    none
 post:   The tasks are retrieved from the file and are added to the list.
 Refer to the saveList() function for the format of tasks in the file
 */
void loadList(DynArr *heap, FILE *filePtr)
{
    TaskP task;
    char line[100];  /* Assume lines < 100 */
    char desc[TASK_DESC_SIZE], *nlptr;
    int priority;
    
    /* Read the priority first, then the description.
     * fgets() is used to read string with spaces
     */
#ifdef NOTDEF
    while (fscanf(filePtr, "%d\t", &priority) != EOF)
    {
        /* fgets() stops reading at \n character */
        fgets(desc, sizeof(desc), filePtr);
        /* remove trailing newline character */
        nlptr = strchr(desc, '\n');
        if (nlptr)
            *nlptr = '\0';
        
        task = createTask(priority, desc);
        addHeap(heap, task);
    }
#endif
    
    while(fgets(line, sizeof(line), filePtr) != 0)
    {
        sscanf(line, "%d\t%[^\n]", &priority, desc);
        task = createTask(priority, desc);
        addHeap(heap, task);
    } /* should use feof to make sure it found eof and not error*/
    
}
Example #2
0
File: hw1.c Project: kepler27/HW1
void changeTeamName(Node ** head, FILE * finTeams)
{
    char temp[MAX];
    char * longName;
    char * myStringCopy;
    Node * first = *head;

    for(; first != NULL; first = first->next)
    {
        fgets(temp, MAX, finTeams);
        while(fgets(temp, MAX, finTeams)!= NULL)
        {
            myStringCopy = (char *)calloc(strlen(temp)+1, sizeof(char));
            strcpy(myStringCopy,temp);
            char * toke = strtok(myStringCopy, ",");
            longName = (char*) calloc(strlen(toke)+1,sizeof(char));
            strcpy(longName, toke);
            toke = strtok(NULL, ",");
            stripRN(toke);
            if(strcasecmp(((Player*)(first->data))->teamName, toke) == 0)
            {
                free(myStringCopy);
                rewind(finTeams);
                free(((Player*)(first->data))->teamName);
                ((Player*)(first->data))->teamName = longName;
                break;
            }
            free(longName);
            free(myStringCopy);
        }
    }
}
Example #3
0
static void initialize_for_reading_file(int *num_solutions_r,
	int *numobj_r, const char *path_file_name){
	FILE * solution_file;	
	char *line;
	char *line_splited;
	int num_obj;
	int num_solutions;
	

	num_solutions = 0;
	num_obj = -1; //Because the first collum is index.
	line = Malloc(char, MAX_LINE_SOLUTION);
	solution_file = open_file(path_file_name, fREAD);

	//getting first line to obtain number of objectivies
	fgets(line,MAX_LINE_SOLUTION,solution_file);
 	line_splited = strtok (line,"\t");
  	while (line_splited != NULL){
    	num_obj = num_obj + 1;
    	line_splited = strtok(NULL, "\t");
  	}	
	//Counting how many lines the file has
	while ( fgets(line,MAX_LINE_SOLUTION,solution_file) != NULL){
		num_solutions = num_solutions + 1;
	}

	fclose(solution_file);
	free(line);

	//Setting return values
	*numobj_r = num_obj;
	*num_solutions_r = num_solutions;

}
Example #4
0
/**
 * @brief Check if given credentials are correct
 * @param user - struct containing username and password for check
 * @return 1 if credentials are valid 0 otherwise
 *
 * Function opens a file with all users and passwords and then it is trying to find given user in the file with all registered users.
 * If we find a user we check if the password is the same as password given at registration if yes returns 1 else 0.
 */
int user_auth(user_t * user){

    //file contains all registered logins and passwords
    FILE * login = fopen("login","r");

    //if file doesn't exist - there are no valid logins and password - credentials are wrong
    if(!login)
        return 0;

    //find given username and password in login file
    char username[BUFFER_SIZE],password[BUFFER_SIZE];
    while(fgets(username,BUFFER_SIZE,login)!=NULL){
        fgets(password,BUFFER_SIZE,login);
        username[strlen(username)-1]='\0';
        password[strlen(password)-1]='\0';
        
        //if we found suitable username and password credentials are OK
        if(!strcmp(user->username,username) && !strcmp(user->password,password)){
            fclose(login);
           return 1;
        }
    }
    fclose(login);
    //we didn't find given login and password
    return 0;
}
Example #5
0
File: bat.c Project: gabeg805/Atlas
// Return the battery charge level
static int get_charge() {
    
    // Initialize file handler
    FILE *handle;
    
    // Get contents of NOW file
    handle = fopen(CHARGE_NOW_FILE, "r");
    char charge_now[10];
    fgets(charge_now, sizeof(charge_now), handle);    
    fclose(handle);
    
    // Get contents of FULL file
    handle = fopen(CHARGE_FULL_FILE, "r");
    char charge_full[10];
    fgets(charge_full, sizeof(charge_full), handle);    
    fclose(handle);
    
    // Get contents of STATUS file
    handle = fopen(CHARGE_STATUS_FILE, "r");
    char charge_status[10];
    fgets(charge_status, sizeof(charge_status), handle);    
    fclose(handle);
    
    // Calculate charge
    int charge;
    if ( strcmp(charge_status, "Charging\n") == 0 ) 
        charge = -1;
    else {
        int now = atoi(charge_now);
        int full = atoi(charge_full);
        charge = 100.0f * now / full;
    }
    
    return charge;
}    
Example #6
0
void
SilentWait (void)
{
char	dummy[80];
#ifdef UNIX
FILE	*tty;
#endif
/**
 ** Get anything typed including '\n' if stderr does NOT go to a file
 ** or else the user may be invisibly prompted.
 **
 ** According to a suggestion from A. Bagge, in UNIX pipe mode stdin
 ** will be replaced by /dev/tty.
 **/
  if (!Logfile_flag)
  {
#ifdef UNIX
	if ((tty = fopen("/dev/tty","r")) != NULL)
	{
		fgets (dummy, 80, tty);
		fclose(tty);
	}
	else
#endif
		fgets (dummy,80,stdin);
  }
}
Example #7
0
File: Ase.cpp Project: RinM/CGA
void CLoadASE::GetTextureInfo (tMaterialInfo *pTexture, int desiredMaterial)
{
	char strWord[255] = {0};
	int materialCount= 0;
	
	rewind(m_FilePointer);

	while (!feof(m_FilePointer))
	{
		fscanf(m_FilePointer, "%s", &strWord);

		if (!strcmp(strWord, MATERIAL))
		{
			materialCount++;

			if(materialCount == desiredMaterial)
				break;
		}
		else
		{
			fgets(strWord, 100, m_FilePointer);
		}
	}

	while (!feof(m_FilePointer))
	{
		fscanf(m_FilePointer, "%s", &strWord);

		if (!strcmp (strWord, MATERIAL))
		{
			return;
		}
		else if (!strcmp(strWord, MATERIAL_COLOR))
		{
			fscanf(m_FilePointer, " %f %f %f", &(pTexture->fColor[0]), 
											   &(pTexture->fColor[1]), 
											   &(pTexture->fColor[2]));
		}
		else if (!strcmp(strWord, TEXTURE))
		{
			GetTextureName(pTexture);
		}
		else if (!strcmp(strWord, MATERIAL_NAME))
		{
			GetMaterialName(pTexture);
		}
		else if(!strcmp(strWord, UTILE))
		{
			pTexture->uTile = ReadFloat();
		}
		else if(!strcmp(strWord, VTILE))
		{
			pTexture->vTile = ReadFloat();
		}
		else
		{
			fgets (strWord, 100, m_FilePointer);
		}
	}
}
Example #8
0
int main() {
  FILE* in = stdin;
#ifdef LOCAL_TEST
  in = fopen("input.txt", "r");
  if(!in) return -1;
#endif


  char buf[16]; 
  int start=-1;
  int end=-1;
  fgets(buf,sizeof(buf),in);
  int count=0;
  while(fgets(buf,sizeof(buf),in)){
    if(start<0){
      start=strtol(buf,NULL,10);
    } else {
      end=strtol(buf,NULL,10);
      if(!(start&1)) start++;
      if(!(end&1)) end--;
      int result;
      if(end>=start){
	const int n=(end-start)>>1;
	result=start*(n+1) + n*(n+1);
      } else result=0;
      count++;
      printf("Case %d: %d\n",count,result);
      start=-1;
    }
  }
Example #9
0
int read_input_file(void) {
	char line[80];
	FILE *in;

	fprintf(stderr, "\nReading Input File ... ");

	in = fopen(config_filename, "r");
	if (in == NULL) {
		fprintf(stderr, "Error! hf2_display could not open input file: %s\n",
				config_filename);
		exit(-1);
	}
	while (fgets(line, sizeof(line), in) != 0) {
		if (strncmp(line, "TMP", 3) == 0) {
			fgets(tmp_dir, sizeof(tmp_dir), in);
			tmp_dir[strlen(tmp_dir) - 1] = 0;
			fprintf(stderr, "\nFound TMP_DIR=%s", tmp_dir);
		}
		if (strncmp(line, "DATA", 4) == 0) {
			fgets(data_dir, sizeof(data_dir), in);
			data_dir[strlen(data_dir) - 1] = 0;
			fprintf(stderr, "\nFound DATA_DIR=%s", data_dir);
		}
	}
	fclose(in);

	return (1);
}
Example #10
0
File: mysql3.c Project: llxp/llxp
void filmdaten_loeschen(void) {
   char del[255], temp[4];
   char *item[]= {"titel", "hauptrolle", "fsk", "gedreht" };
   char *ptr;
   char *str[5], *query='\0';
   int auswahl, i, size=0;
   unsigned long affected;

   printf("Nach welchem Kriterium wollen Sie Daten loeschen\n");
   printf("[1]=Titel  [2]=Hauptrolle  [3]=FSK  "
          "[4]=Datum  : [ ]\b\b");

   fgets(temp, 3, stdin);
   if( (ptr = strchr(temp, '\n')) != NULL)
      *ptr = '\0';  /* newline durch \0 ersetzen */
   sscanf(temp, "%d", &auswahl);

   str[0] = "DELETE FROM filmdaten WHERE ";
   if(auswahl > 0 && auswahl < 5) {
      str[1] = malloc(strlen(item[auswahl-1])+1);
      strcpy(str[1], item[auswahl-1]);
   }
   else {
      printf("Kein solches Kriterium vorhanden!!!\n\n");
      return;
   }
   str[2] = " = '";

   printf("Bitte angaben fuer \'%s\' machen: ",
      item[auswahl-1]);
   fgets(del, 254, stdin);
   if( (ptr = strchr(del, '\n')) != NULL)
      *ptr = '\0';  /* newline durch \0 ersetzen */
   str[3] = malloc(strlen(del)+1);
   strcpy(str[3], del);
   str[4] = "'";

   for (i=0; i < 5; i++)
      size+=strlen(str[i]);
   /* Speicherplatz für den Anfragestring reservieren */
   query = malloc(size + 1);
   strcpy(query, str[0]);
   for(i = 1; i < 5; i++)
      strcat(query, str[i]);
   /* als Test für die Konsole */
   /* printf("%s",query);      */

   /* jetzt die Anfrage an den Datenbankserver */
   mysql_real_query(mysql, query, strlen(query));
   check_error();
   if((affected=(unsigned long)mysql_affected_rows(mysql))<= 0 ){
      printf("Kein Datensatz von dieser Anfrage betroffen\n");
      check_error();
   }
   else
       printf("%ld %s von dieser Anfrage betroffen\n\n",
        affected, (affected == 1) ? "Datensatz war" :
        "Datensaetze waren" );
   free(query);
}
Example #11
0
File: mysql3.c Project: llxp/llxp
/* Daten mit mysql_real_query() in die Datenbank schreiben */
void filmdaten_anfuegen(void) {
   char titel[255], hauptrolle[255], temp[6];
   unsigned int fsk, gedreht;
   int i,  size=0;
   char *str[9], *query;
   char *ptr;

   printf("\n\nFilmtitel  : ");
   fgets(titel, 254, stdin);
   if( (ptr = strchr(titel, '\n')) != NULL)
      *ptr = '\0';  /* newline durch \0 ersetzen */

   printf("Hauptrolle : ");
   fgets(hauptrolle, 254, stdin);
   if( (ptr = strchr(hauptrolle, '\n')) != NULL)
      *ptr = '\0';  /* newline durch \0 ersetzen */

   printf("FSK        : ");
   fgets(temp, 4, stdin);
   if( (ptr = strchr(temp, '\n')) != NULL)
      *ptr = '\0';  /* newline durch \0 ersetzen */
   sscanf(temp, "%u", &fsk);

   printf("Gedreht    : ");
   fgets(temp, 5, stdin);
   if( (ptr = strchr(temp, '\n')) != NULL)
      *ptr = '\0';  /* newline durch \0 ersetzen */
   sscanf(temp, "%u", &gedreht);

   /* jetzt wird der Anfragestring erstellt */
   str[0]= "INSERT INTO filmdaten (titel, hauptrolle, fsk, "
            "gedreht) VALUES ('";
   str[1] = malloc(strlen(titel)+1);
   strcpy(str[1], titel);
   str[2] = "','";
   str[3] = malloc(strlen(hauptrolle)+1);
   strcpy(str[3], hauptrolle);
   str[4] = "',";
   str[5] = malloc(3);
   sprintf(str[5], "%2u", fsk);
   str[6] = ",";
   str[7] = malloc(5);
   sprintf(str[7], "%4u", gedreht);
   str[8] = ")";

   for (i=0; i < 9; i++)
      size+=strlen(str[i]);
   /* Speicherplatz für den Anfragestring reservieren */
   query = malloc(size + 1);
   strcpy(query, str[0]);
   for(i = 1; i < 9; i++)
      strcat(query, str[i]);
   /* zum Testen für die Konsole  */
   /* printf("%s",query);         */

   /* jetzt die Anfrage an den Datenbankserver */
   mysql_real_query(mysql, query, strlen(query));
   check_error();
   free(query);
}
void cargar(){
		//FILE *archivo;
		archivo=fopen("/home/jorge/Documentos/sistemas 2016/Programacion-Imperativa/prueba.txt", "a+");
	
		printf("Ingrese el Nombre: \n");
		fgets(Contacto.nombre, 50, stdin);// se usa para cargar string con espacios asigna nombre de la variable, longitoud  y forma de ingreso
		printf("Ingrese el Apellido: \n");
		fgets(Contacto.apellido, 50, stdin);
		printf("Ingrese direccion: \n");
		fgets(Contacto.direccion, 50, stdin);
		printf("Ingrese ciudad: \n");
		fgets(Contacto.ciudad, 50, stdin);
		printf("Ingrese telefono: \n");
		fgets(Contacto.telefono, 20, stdin);
		//fflush(stdout);
		/*while(scanf("%d",&Contacto.telefono)!=1){ //escanea o recibe un valor, si no es entero lo hace hasta que se ingrese un numero interger
			printf("vuelva a intentarlo con un numero:  ");
			while(getchar() != '\n');// sentencia que permite salir de un bucle infiniro del bucle anterior espera hasta que hay un cambio de linea
		}*/
		//getchar();// toma el enter despues del interger, sino es tomado por el primer fgets() o scanf() siguente como valor vacio
		system("clear");// limpia la pantalla para cargar el nuevo libro
		fprintf(archivo,"%s", Contacto.nombre);
		fprintf(archivo,"%s", Contacto.apellido);
		fprintf(archivo,"%s", Contacto.direccion);
		fprintf(archivo,"%s", Contacto.ciudad);
		fprintf(archivo,"%s\n", Contacto.telefono);
	fclose(archivo);
	
}
Example #13
0
int input_data(ADDRESS_BOOK *config, struct address_data *data)
{
    char buf[1024];
    char *str;
    char conv[2] = "0";
    int i;

    printf("Enter name: ");
    fgets(buf, sizeof(buf), stdin);
    for(str = buf; *str != '\0'; str++)
        if(*str == '\n') *str = '\0';
    strncpy(data->name, buf, sizeof(data->name));
    printf("Enter address: ");
    fgets(buf, sizeof(buf), stdin);
    for(str = buf; *str != '\0'; str++)
        if(*str == '\n') *str = '\0';
    strncpy(data->address, buf, sizeof(data->address));
    data->no = ++config->last_id;
    printf("Enter phone number: ");
    fgets(buf, sizeof(buf), stdin);
    for(i = 0; buf[i] != '\0'; i++) {
        conv[0] = buf[i];
        data->phone[i] = atoi(conv);
        if(i > sizeof(data->phone)) break;
    }
    buf[i] = END_OF_PHONE_NUMBER;
    data->status = (0x01 << ACTIVE);

    return 0;
}
Example #14
0
int load_file(ADDRESS_BOOK *config)
{
    FILE *fp;
    char buf[1024];
    char *filename = config->filename;
    int width_name, width_address;
    struct address_data data;

    fp = fopen(filename, "r");
    if(!fp) {
        fprintf(stderr, "Error: file open [%s]\n", filename);
        return -1;
    }
    while(1) {
        if(fgets(buf, sizeof(buf), fp) == 0) break;
        config->last_id = atoi(buf);
    }
    fseek(fp, 0, SEEK_SET);
    for(width_name = 0, width_address = 0; ;) {
        if(fgets(buf, sizeof(buf), fp) == 0) break;
        data = decode_data(buf);
        if(width_name < strlen(data.name))
            width_name = strlen(data.name);
        if(width_address < strlen(data.address))
            width_address = strlen(data.address);
    }
    config->width_name = width_name;
    config->width_address = width_address;
    fclose(fp);
    return 0;
}
Example #15
0
int get_user_reply(struct fdisk_context *cxt, const char *prompt,
			  char *buf, size_t bufsz)
{
	char *p;
	size_t sz;

	do {
	        fputs(prompt, stdout);
		fflush(stdout);

		if (!fgets(buf, bufsz, stdin)) {
			if (fdisk_label_is_changed(fdisk_get_label(cxt, NULL))) {
				fprintf(stderr, _("\nDo you really want to quit? "));

				if (fgets(buf, bufsz, stdin) && !rpmatch(buf))
					continue;
			}
			fdisk_free_context(cxt);
			exit(EXIT_FAILURE);
		} else
			break;
	} while (1);

	for (p = buf; *p && !isgraph(*p); p++);	/* get first non-blank */

	if (p > buf)
		memmove(buf, p, p - buf);		/* remove blank space */
	sz = strlen(buf);
	if (sz && *(buf + sz - 1) == '\n')
		*(buf + sz - 1) = '\0';

	DBG(ASK, ul_debug("user's reply: >>>%s<<<", buf));
	return 0;
}
Example #16
0
static int nr_ax25_aton (char *address, struct full_sockaddr_ax25 *addr)
{
	char buffer[100], *call, *alias;
	FILE *fp;
	int addrlen;

	for (call = address; *call != '\0'; call++)
		*call = toupper (*call);

	if ((fp = fopen (PROC_NR_NODES_FILE, "r")) == NULL)
	{
		fprintf (stderr, "call: NET/ROM not included in the kernel\n");
		return -1;
	}
	fgets (buffer, 100, fp);

	while (fgets (buffer, 100, fp) != NULL)
	{
		call = strtok (buffer, " \t\n\r");
		alias = strtok (NULL, " \t\n\r");

		if (strcmp (address, call) == 0 || strcmp (address, alias) == 0)
		{
			addrlen = ax25_aton (call, addr);
			fclose (fp);
			return (addrlen == -1) ? -1 : sizeof (struct sockaddr_ax25);
		}
	}

	fclose (fp);

	fprintf (stderr, "call: NET/ROM callsign or alias not found\n");

	return -1;
}
int main() {
    FILE *ifp;
    char line[MAX];
    char** tab;
    int col,ctr=0,row=0;
    tab=(char**)malloc(MAX*sizeof(char*));
    ifp = fopen("maze.in","r");

    if (ifp == NULL)
        printf("I couldn't open results.dat for writing.\n");

    else{
        while (fgets(line, MAX, ifp) != NULL) {
            col=strlen(line);
            row++;
        }
        for (ctr = 0; ctr<row; ctr++) {
            tab[ctr] = (char *) malloc(MAX * sizeof(**tab));
        }
        ctr=0;
        ifp = fopen("maze.in","r");
        while (fgets(line, MAX, ifp) != NULL){
            strcpy(tab[ctr],line);
            tab[ctr][col]='\0';
            ctr++;
        }
        printf("EMPTY MAZE!\n\n");
        display(tab,row,col,0);
        printf("\n\nSOLVED MAZE!\n\n");
        display(tab,row,col,1);
        fclose(ifp);
    }

    return 0;
}
Example #18
0
int main () {
    char s[50],*command,*archivename,*filename;
    fgets(s,512,stdin);
    command=strtok(s," \n");
    while ( strcmp(command,"quit") != 0) {
        
        if (strcmp(command,"load")==0) {
            archivename=strtok(NULL," \n");
            load (archivename);
        }
            if ( strcmp(command,"list") == 0) 
        {   archivename=strtok(NULL," \n");
            list(archivename);
        }
        
        if ( strcmp(command,"get") == 0)
        {   archivename=strtok(NULL," \n");
            filename=strtok(NULL," \n");
            get(archivename,filename);
        }
       
        fgets(s,512,stdin);
        command=strtok(s," \n");
    }
return 0;
}
Example #19
0
/*
 * Return 0 if the files are different, 1 if the files are the same.
 */
static int compare_file(const char *outfn, const char *newfn)
{
	FILE	*old_f, *new_f;
	char	oldbuf[2048], newbuf[2048], *oldcp, *newcp;
	int	retval;

	old_f = fopen(outfn, "r");
	if (!old_f)
		return 0;
	new_f = fopen(newfn, "r");
	if (!new_f) {
		fclose(old_f);
		return 0;
	}

	while (1) {
		oldcp = fgets(oldbuf, sizeof(oldbuf), old_f);
		newcp = fgets(newbuf, sizeof(newbuf), new_f);
		if (!oldcp && !newcp) {
			retval = 1;
			break;
		}
		if (!oldcp || !newcp || strcmp(oldbuf, newbuf)) {
			retval = 0;
			break;
		}
	}
	fclose(old_f);
	fclose(new_f);
	return retval;
}
Example #20
0
int
main(int argc, char *argv[])
{
	FILE *fp;
	char buf[256], *ptr;
	int i, j;
	fp = popen("ldd /home/bbs/bin/bbs|grep libc", "r");
	if (!fp) {
		printf("Error!\n");
		return -1;
	}
	fgets(buf, sizeof (buf), fp);
	pclose(fp);
	ptr = strchr(buf, '(');
	if (!ptr) {
		printf("ldd error!\n");
		return -1;
	}
	strtok(ptr + 1, ")");
	i = strtol(ptr + 1, NULL, 16);
	while (fgets(buf, sizeof (buf), stdin)) {
		fputs(buf, stdout);
		ptr = strrchr(buf, 'x');
		if (!ptr || ptr == buf || '0' != *(ptr - 1))
			continue;
		j = strtol(ptr - 1, NULL, 16);
		snprintf(buf, sizeof (buf),
			 "addr2line -e /usr/lib/debug/libc.so.6 0x%x", j - i);
		system(buf);
	}
	return 0;
}
void move(char **libs, int n){
	char mova[100];
	char aux[100], head[100], bibli[100];
	int i=0;/*Declara e INICIALIZA O CONTADOR*/
	FILE *arq;
	if((arq=fopen("dirs.txt", "r"))==NULL){
		printf("Não foi possivel encontrar o diretorio pra mover os arquivos");
		exit(1);/*fecha o programa*/
	}
	fgets(head,50,arq);/*pega os endereços */
	fgets(bibli,50,arq);
	fclose(arq);
	if(n>0)
		printf("\nMovendo os arquivos!\n");
	while(i<n){/*percorre a lista  de bibliotecas ate ofim*/
		mova[0]='\0';/*zera a varivael para  não montar um comando no fim de outro*/
		strcat(mova,"move ");/*o comando "move"*/
		strcat(mova,libs[i]);/*adiciona a biblioteca a ser movida*/
		strcat(mova," ");/*espaço*/
		strcat(mova,bibli);/*adiciona o diretorio*/
		system(mova);/*move o arquivo*/
		strcpy(aux,libs[i]);/*copia a biblioteca em uma variavel auxiliar, para evitar perca de dados*/
		mova[0]='\0';/*zera para montar o comando para o arquivo .H  */
		aux[strlen(aux)-1]='h';/*coloca um H no luga do C*/
		strcat(mova,"move ");/*comando*/
		strcat(mova,aux);/*adiciona o header a ser movida*/
		strcat(mova," ");/*espaço*/
		strcat(mova,head);/*adiciona o diretorio*/
		system(mova);/*move o arquivo*/
		i++;
	}
}
Example #22
0
char *fgetl(FILE *fp)
{
    if(feof(fp)) return 0;
    size_t size = 512;
    char *line = malloc(size*sizeof(char));
    if(!fgets(line, size, fp)){
        free(line);
        return 0;
    }

    size_t curr = strlen(line);

    while((line[curr-1] != '\n') && !feof(fp)){
        if(curr == size-1){
            size *= 2;
            line = realloc(line, size*sizeof(char));
            if(!line) {
                printf("%ld\n", size);
                malloc_error();
            }
        }
        size_t readsize = size-curr;
        if(readsize > INT_MAX) readsize = INT_MAX-1;
        fgets(&line[curr], readsize, fp);
        curr = strlen(line);
    }
    if(line[curr-1] == '\n') line[curr-1] = '\0';

    return line;
}
void CWE252_Unchecked_Return_Value__char_fgets_12_bad()
{
    if(globalReturnsTrueOrFalse())
    {
        {
            /* By initializing dataBuffer, we ensure this will not be the
             * CWE 690 (Unchecked Return Value To NULL Pointer) flaw for fgets() and other variants */
            char dataBuffer[100] = "";
            char * data = dataBuffer;
            printLine("Please enter a string: ");
            /* FLAW: Do not check the return value */
            fgets(data, 100, stdin);
            printLine(data);
        }
    }
    else
    {
        {
            /* By initializing dataBuffer, we ensure this will not be the
             * CWE 690 (Unchecked Return Value To NULL Pointer) flaw for fgets() and other variants */
            char dataBuffer[100] = "";
            char * data = dataBuffer;
            printLine("Please enter a string: ");
            /* FIX: check the return value */
            if (fgets(data, 100, stdin) == NULL)
            {
                printLine("fgets failed!");
                exit(1);
            }
            printLine(data);
        }
    }
}
Example #24
0
int main(int argc, char* argv[]){
	FILE *input_file = fopen(argv[1], "r");
	FILE *output_file = fopen("course_content", "a+");
	while(fgets(content, MAX, input_file) != NULL){
		if(strcmp(content, "<課程識別碼>\n") == 0){
			fgets(content, MAX, input_file);
			fputs("<c>\n", output_file);
			fputs(content, output_file);
		}
		else if(strcmp(content, "<課程概述>\n") == 0){ // fgets eat newline??
			while(fgets(content, MAX, input_file) != NULL){
				if(strcmp(content, "</>\n") == 0) break;
				fputs(content, output_file);
			}
			break;
		}
	}
	if(ferror(input_file)){
		printf("the buffer is too small\n");
		exit(1);
	}

	fputs("</>\n", output_file);

	fclose(input_file);
	fclose(output_file);

	return 0;
}
Example #25
0
int32_t getline777(char *line,int32_t max)
{
#ifndef _WIN32
    static char prevline[1024];
    struct timeval timeout;
    fd_set fdset;
    int32_t s;
    line[0] = 0;
    FD_ZERO(&fdset);
    FD_SET(STDIN_FILENO,&fdset);
    timeout.tv_sec = 0, timeout.tv_usec = 10000;
    if ( (s= select(1,&fdset,NULL,NULL,&timeout)) < 0 )
        fprintf(stderr,"wait_for_input: error select s.%d\n",s);
    else
    {
        if ( FD_ISSET(STDIN_FILENO,&fdset) > 0 && fgets(line,max,stdin) == line )
        {
            line[strlen(line)-1] = 0;
            if ( line[0] == 0 || (line[0] == '.' && line[1] == 0) )
                strcpy(line,prevline);
            else strcpy(prevline,line);
        }
    }
    return((int32_t)strlen(line));
#else
    fgets(line, max, stdin);
    line[strlen(line)-1] = 0;
    return((int32_t)strlen(line));
#endif
}
Example #26
0
// function definitions
void get_names(names* pn) {
    int i;
    printf("Please enter your first name: ");
    fgets(pn->first, SLEN, stdin);
    i = 0;

    while (pn->first[i] != '\n' && pn->first[i] != '\0') {
        i++;
    }

    if (pn->first[i] == '\n') {
        pn->first[i] = '\0';
    } else
        while (getchar() != '\n') {
            continue;
        }

    printf("Please enter your last name: ");
    fgets(pn->last, SLEN, stdin);
    i = 0;

    while (pn->last[i] != '\n' && pn->last[i] != '\0') {
        i++;
    }

    if (pn->last[i] == '\n') {
        pn->last[i] = '\0';
    } else
        while (getchar() != '\n') {
            continue;
        }
}
Example #27
0
int modify_passwd(SSL *ssl,int order)
{
	ACCOUNT user;
	int ack;
	modify_passwd_ui();
	echo_mode(STDIN_FILENO,ECHO_OFF);	/* set echo off */
	printf(YELLOW"Old Password: ");	
	fgets(user.passwd,PASSWD_SIZE,stdin);	
	user.passwd[strlen(user.passwd)-1] = '\0';
	/* verify old password */
	if(strcmp(LOGIN_USER.passwd,user.passwd) == 0)
	{
		printf("\nNew Passwd: ");
		fgets(user.passwd,PASSWD_SIZE,stdin);	
		user.passwd[strlen(user.passwd)-1] = '\0';
		strcpy(user.name,LOGIN_USER.name);
		account_send(ssl,user,order);	
	}
	else
	{
		printf(RED"\nPassword error!\n"NONE);
	}
	ack = sftpack_recv_ack(ssl,order);	
	if( ack == PASSWD_OK)
	{
		printf("\nPasswd modify succeed!\n");	
		LOGIN_USER=user;
	}
	echo_mode(STDIN_FILENO,ECHO_ON);	/* set echo off */
	return 0;
}
int main()
{
    int i;
    int num[MAX];                            //存放10个数
    char str[LEN];                           //读取,写入文件缓冲
    FILE *fp;                                //文件指针

    fp = fopen("number","w+");

    if(fp == NULL)
    {
        printf("fopen file error !\n");
        exit(ERROR);
    }
 
    num_to_file(fp);                         //将数写入文件

    fseek(fp,0,SEEK_SET);
    fgets(str,LEN,fp);
    printf("the old num : %s\n",str);        //打印出文件内容

    fseek(fp,0,SEEK_SET);
    file_to_num(fp,num);                     //将文件读出并转换成数组
     
    order_num(num);                          //对数组进行排序
 
    fseek(fp,0,SEEK_SET);
    order_to_file(fp,num);                   //将新数组写入文件

    fseek(fp,0,SEEK_SET);
    fgets(str,LEN,fp);                       //读出文件并打印出文件内容
    printf("the ordering num : %s\n",str);  

    return 0;
}
Example #29
0
int main () {
  int count;
  int i, j, k;
  int n;

  scanf ("%d", &count);
  for (i=0; i<count; i++) {
    memset (flag, 0, sizeof(int)*N);
    scanf ("%d", &n);
    getchar();
    for (j=0; j<n; j++)
      fgets (s[j], sizeof(s[j][0])*M, stdin); 
    for (j=0; j<n; j++)
      fgets (d[j], sizeof(d[j][0])*M, stdin);

    /* find immobile sequence */
    for (j=n-1, k=n-1; j>=0; j--) {
      if (!strcmp (s[j],d[k])) { 
        flag[k] = 1;
        k -= 1;
      }
    }
    /* output mobile sequence */
    for (j=n-1; j>=0; j--) {
      if (flag[j] != 1)
        printf ("%s", d[j]);
    }

    printf ("\n");
  }
  return 0;
}
Example #30
0
void adjustafm(FILE *input, FILE *output) {
	int i, k, n, code, width;
	int xll, yll, xur, yur;
	int nxll, nyll, nxur, nyur;
	char name[MAXNAMELEN], base[2];

/* scan for StartCharMetrics */
	for(;;) {
		fgets(line, MAXLINE, input);
		fputs(line, output);
		if (strstr(line, "StartCharMetrics") != NULL) break;
	}
/* process up to EndCharMetrics */
	for (;;) {
		fgets(line, MAXLINE, input);
		if (strstr(line, "EndCharMetrics") != NULL) break;
		if (sscanf(line, "C %d ; WX %d ; N %s ; B %d %d %d %d ;%n",
			&code, &width, &name, &xll, &yll, &xur, &yur, &n) < 7) {
		}
/*	assuming that xll gives sbx accurately */
		if (code >= 0) {	/* override stuff from AUX file */
			xlls[code] = xll; ylls[code] = yll;
			xurs[code] = xur; yurs[code] = yur;			
		}
		fputs(line, output);
	}
	fputs(line, output); /* output EndCharMetrics line */
}