How does fread know when the file is over in C?
74,446
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.
Author by
user202925
Updated on May 28, 2021Comments
-
user202925 almost 3 years
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.
-
autistic about 11 yearsI 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. -
user123 about 11 yearsThanks 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!
-
autistic about 11 yearsIndeed. 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.
-
space_mill over 2 yearsbut what if the file has say 4 characters?