简体   繁体   中英

fgets doesn't work -

Suddenly fgets stoped working while i haven't done any change that will affect the function here is my code .please let me know why it is not working !?

  void readInfo()
{struct grades *grades=malloc(3*sizeof(grades));
   char line[60],str[6];
   int i=0;

   FILE *rf=fopen("Grades.txt","r");
   if(!feof(rf)&&fgets(line,60,rf)!=NULL)

   {           puts("inside if1");


         while(i<3)
         {

             sscanf(line,"%d %s %c",&(grades[i]).ID,str,&(grades[i].grade));
            strcpy(str,((*(grades+i)).course));
                        i++;
            printInfo(grades+i);puts("herwr");
         }

   }
   fclose(rf);
}

*********CODE EDITED

Here's a rewrite of your code:

Uncompiled, much less tested.

void readInfo(void)
{    
    int i = 0;
    FILE *rf = fopen("Grades.txt", "r");
    if (rf != NULL)
    {
        char line[1024];
        while (fgets(line, sizeof(line), rf) != NULL)
        {
            struct grades grade;
            puts("inside while");
            if (sscanf(line, "%d %s %c", &grade.ID, grade.course, &grade.grade) == 3)
            {
                i++;
                printInfo(&grade);
            }
        }
        puts("here");
        fclose(rf);
    }
    printf("%d grades accepted\n", i);
}

Changes include:

  • Not allocating an array for grades — you never reuse the value.
  • No problem with the missing free() .
  • Testing that the file was opened.
  • Not trying to close the file if it was not opened.
  • Allowing for bigger lines — it is painless and avoids problems.
  • Checking that the sscanf() was successful.
  • Printing the number of grades accepted.

Other possibilities:

  • Remove diagnostic prints. They're temporary, but can be useful when things aren't working as you want.
  • It would be better if the file name was passed as an argument to the function.
  • It would probably be better if there was an error report if the file could not be opened (and the message should include the file name), normally written to standard error.
  • If you want to process up to three grade lines, you can do that.
  • If you want to process an indefinite number of grade lines, you can do that.
  • If you want to return the array of grades, you can do that (but how do you say how big the array is — there are multiple possibilities).

All those require some changes to the coding, though nothing very outrageously complex.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM