简体   繁体   中英

fgetc Always returns EOF

While Trying to count the number of lines in a text file, I noticed that fgetc is always returning EOF. This code was working on Freebsd 10 but now it's not working on Mac OSX. I checked the file to see if it was empty, it's not, it's about 1 KB in size and contains 16 lines. I added a line to seek to the beginning of the file thinking that's the problem, but it's still returning EOF. So why is fgetc always returning EOF?

 int getLines(int listFd, int *lines)
 {

     /* Declarations */
     *lines = 0;
     int ch;
     FILE *list;

     /* Get File Stream */
     list = fdopen(listFd, "r");
     if(list == NULL)
     {
         printf("Can't Open File stream\n");
         return -1;
     }

     /* Seek To beginning Of file */
     fseek(list, 0, SEEK_SET);

     /* Get Number of Lines */
     while(!feof(list))
     {
         ch = fgetc(list);
         if(ch == '\n')
         {
             lines++;
         }

         else if(ch == EOF)
         {
             break;
         }
     }

     printf("lines: %d\n", *lines);

     /* Clean up and Exit */
     fclose(list);

    return 0;
}

fgetc() should eventually return EOF . Code's other problem is certainly confusing the behavior and diagnosis. Good to test results of IO funcitons.

int getLines(int listFd, int *lines) {
  ...
  *lines = 0;
  ...
  if (fseek(list, 0, SEEK_SET)) puts("Seek error");
  ...
    ch = fgetc(list);
    if (ch == '\n') {
      // lines++;
      (*lines)++;  // @R Sahu 
    }
   ...
   printf("lines: %d\n", *lines);

   if (ferror(list)) puts("File Error - unexpected");
   if (feof(list)) puts("File EOF - expected");
}

Other stuff:

The below code is a redundant test of the end-of-file condition

/* Get Number of Lines */
while(!feof(list)) {
  ch = fgetc(list);
  ...
  else if(ch == EOF) {
    break;
  }
}

Suggested simplification (@Keith Thompson)

 /* Get Number of Lines */
 while( (ch = fgetc(list)) != EOF) {
   if(ch == '\n') {
     (*lines)++;
   }
 }

Minor point about file line count: If the file had text after the final '\\n' , would that count as a line? Suggest:

*lines = 0;
int prev = '\n'; 
/* Get Number of Lines */
while( (ch = fgetc(list)) != EOF) {
  if(prev == '\n') {
    (*lines)++;
  }
  prev = ch;
}

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