| << Prev | Beej's Guide to C | Next >> |
Determine if a file has reached end-of-file or if an error has occurred.
#include <stdio.h> int feof(FILE *stream); int ferror(FILE *stream); void clearerr(FILE *stream);
Each
The functions feof() and ferror() give you a simple way to test these flags: they'll return non-zero (true) if they're set.
Once the flags are set for a particular stream, they stay that way until you call clearerr() to clear them.
feof() and ferror() return non-zero (true) if the file has reached EOF or there has been an error, respectively.
// read binary data, checking for eof or error
int main(void)
{
int a;
FILE *fp;
fp = fopen("binaryints.dat", "rb");
// read single ints at a time, stopping on EOF or error:
while(fread(&a, sizeof(int), 1, fp), !feof(fp) && !ferror(fp)) {
printf("I read %d\n", a);
}
if (feof(fp))
printf("End of file was reached.\n");
if (ferror(fp))
printf("An error occurred.\n");
fclose(fp);
return 0;
}
| << Prev | Beej's Guide to C | Next >> |