How to find out when a file ended in C?

So I'm not quite sure how to use fread. I have a binary 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 still have:

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 yet, but I just don’t know how to get the so-called “progress”, so to speak. Any help would be appreciated.

+5
source share
1 answer

This is not how you read correctly from a file in C.

freadreturns a size_trepresenting the number of items read.

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

if (file) {
    /* File was opened successfully. */

    /* Attempt to read */
    while (fread(buffer, 1, 4, file) == 4) {
        /* byte swap here */
    }

    fclose(file);
}

As you can see, the above code stopped reading as soon as it freadretrieves anything other than 4 elements.

+13
source

All Articles