How does fread know when the file is over in C?
Asked Answered
U

1

16

So I'm not entirely sure how to use fread. I have a binary file in little-endian that I need to convert to big-endian, and I don't know how to read the file. Here is what I have so far:

FILE *in_file=fopen(filename, "rb");
char buffer[4];
while(in_file!=EOF){
    fread(buffer, 4, 1, in_file);
    //convert to big-endian.
    //write to output file.
}

I haven't written anything else yet, but I'm just not sure how to get fread to 'progress', so to speak. Any help would be appreciated.

Uruguay answered 29/3, 2013 at 5:21 Comment(3)
Complete the program and run it! fread will read from where it left off the last time round the loop. You should check the return value from fread. infile is not likely to compare equal to EOF.Lungworm
For one, "rb" means Read Binary, so your array should be of type int, not char.Generalization
I actually disagree. The array should be chars. Binary characters are only a single byte while an integer is 4 bytes. So in this case using a char array would be a better representation because one char represents one byte.Pokey
W
33

That's not how you properly read from a file in C.

fread returns a size_t representing the number of elements read successfully.

FILE* file = fopen(filename, "rb");
char buffer[4];

if (file) {
    /* File was opened successfully. */
    
    /* Attempt to read */
    while (fread(buffer, sizeof *buffer, 4, file) == 4) {
        /* byte swap here */
    }

    fclose(file);
}

As you can see, the above code would stop reading as soon as fread extracts anything other than 4 elements.

Waldron answered 29/3, 2013 at 5:24 Comment(4)
I suggest while (fread(buffer, 1, 4, file) == 4) { ... } in order to ensure that 4 bytes are read and avoid the undefined behaviour of using uninitialised values.Quathlamba
Thanks for bringing that up. I just realized that I should be using 1 for the size and 4 for the count. Also, awesome name bro!Waldron
Indeed. I hadn't noticed that, however. My comment was in regards to explicitly comparing the return value to 4, rather than 0, because if fread were to return 3, 2 or 1 then there would be uninitialised bytes in buffer, which would result in undefined behaviour if those values were used.Quathlamba
but what if the file has say 4 characters?Abagail

© 2022 - 2024 — McMap. All rights reserved.