Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c

file-io

fread

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.

like image 588
user202925 Avatar asked Mar 29 '13 05:03

user202925


1 Answers

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.

like image 93
user123 Avatar answered Oct 14 '22 04:10

user123