Advertisement

fgetc

Started by December 04, 2023 07:01 AM
1 comment, last by a light breeze 11 months, 2 weeks ago

I wanted to learn fgetc, so I did a search.

This was the first result:

C library function - fgetc() (tutorialspoint.com)

It has this code:

#include <stdio.h>

int main () {
   FILE *fp;
   int c;
   int n = 0;
  
   fp = fopen("file.txt","r");
   if(fp == NULL) {
      perror("Error in opening file");
      return(-1);
   } do {
      c = fgetc(fp);
      if( feof(fp) ) {
         break ;
      }
      printf("%c", c);
   } while(1);

   fclose(fp);
   return(0);
}

Am I missing something or isn't this code buggy? If file.txt is one character, won't it break before printing the character?

Thank you.

Mike C.http://www.coolgroups.com/zoomer/http://www.coolgroups.com/ez/

See https://en.cppreference.com/w/c/io/feof:

This function only reports the stream state as reported by the most recent I/O operation, it does not examine the associated data source. For example, if the most recent I/O was a fgetc, which returned the last byte of a file, feof returns zero. The next fgetc fails and changes the stream state to end-of-file. Only then feof returns non-zero.

This topic is closed to new replies.

Advertisement