Q
Q
Qubc2020-02-04 00:59:46
C++ / C#
Qubc, 2020-02-04 00:59:46

How does while ( !feof ( cfPtr ) ) work?

FILE * cfPtr = fopen( "test.txt", "rb" );
    char temp;
    while ( !feof ( cfPtr ) ){
      fread( &temp, sizeof( char ), 1, cfPtr );
      printf("%c\n", temp);
    }

A
B
C
C

The content of test.txt is 414243.
Of course, you can call fread before entering the loop, but this does not give understanding.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
J
jcmvbkbc, 2020-02-04
@Qubc

How does while ( !feof ( cfPtr ) ) work?

As you can see, it doesn't work well. Because man feof tells us that a function returns the status of a thread, and the thread's status only changes when other functions are called.
Therefore, according to all the rules, it would be written like this:
FILE * cfPtr = fopen( "test.txt", "rb" );
char temp;

for (;;) {
  int read = fread( &temp, sizeof( char ), 1, cfPtr );
  if (read == 1) {
    printf("%c\n", temp);
  } else {
    if (feof(cfPtr)) {
      /*случился конец файла*/
    } else if (ferror(cfPtr)) {
      /* случилась ошибка */
    }
    break;
  }
}

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question