Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

feof() in C file handling

I am reading a binary file byte-by-byte,i need determine that whether or not eof has reached.

feof() doesn't works as "eof is set only when a read request for non-existent byte is made". So, I can have my custom check_eof like:

if ( fread(&byte,sizeof(byte),1,fp) != 1) {
    if(feof(fp))
    return true;
}
return false;

But the problem is, in case when eof is not reached, my file pointer is moved a byte ahead. So a solution might be to use ftell() and then fseek() to get it to correct position.

Another solution might be to buffer the byte ahead in some temporary storage.

Any better solutions?

like image 221
sud03r Avatar asked Nov 23 '25 15:11

sud03r


2 Answers

If you're reading a byte at a time, the idiomatic way to do this is with fgetc:

int c;
while ((c = fgetc(fp)) != EOF) {
   // Do something.
}

and then you shouldn't need to deal with feof.

like image 79
jamesdlin Avatar answered Nov 26 '25 05:11

jamesdlin


I typically do something like this:

int get_next_char(FILE* fp, char *ch)
{
    return fread(ch, sizeof(char),1, fp) == 1;
}

// main loop
char ch;
while (get_next_char(fp, &ch))
    process_char(ch);

if (!feof(fp))
    handle_unexpected_input_error(fp);
like image 27
Kristopher Johnson Avatar answered Nov 26 '25 05:11

Kristopher Johnson



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!