Feof () in C file processing

I am reading a byte byte file, I need to determine if eof has reached.

The feof () function does not work because "eof is set only when a read request is made for a byte that does not exist." So, I can have my own custom check_eof, for example:

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

But the problem is that if eof is not reached, my file pointer moves forward bytes. Therefore, the solution may be to use ftell(), and then fseek()to get the right position.

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

Any better solutions?

+3
source share
5 answers

, fgetc:

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

feof.

+6

- :

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);
+3

, , - , (, . ).

, ungetc, , :

int c = fgetc(fp);
if (c == EOF)
{
    // handle eof / error
}
else
{
    ungetc(c, fp);

    // the next read call is guaranteed to return at least one byte

}
+2

, , , EOF , feof() fread(), .
, , :

return feof(fp) ? true : false;
0

:

fseek(myFile, 0, SEEK_END);
fileLen = ftell(myFile);
fseek(myfile, 0, SEEK_SET);

When you first open the file to determine the length. Then tune your reading cycle to never count the end. You can use ftellto find out where you are, and compare with fileLen to find out how much more you need.

0
source

Source: https://habr.com/ru/post/1741011/


All Articles