I'm working in C and trying to read a file system image (eg: name.IMA) and I need it in binary form because I need to read it byte by byte. What is the correct way to read these type of files in C? The below does not work:
FILE *filePointer = fopen("name.IMA","rb");
fread(buffer, fileLength, 1, filePointer);
MAIN PROBLEM: The fread() is actually opening and reading as expected. The confusion is because of the return value given by fread() is for some reason equal to 1 (even though way more than 1 byte was read). What's the issue here?
If your fread
line is not doing what you expected, I'd be looking at whatever fileLength
is set to. If it's more bytes than can be read, then the fread
will return zero.
One thing you need to keep in mind is that fread()
returns the number of items read, not the number of bytes (my emphasis):
size_t fread (void *ptr, size_t size, size_t nmemb, FILE *stream);
On success,
fread()
return the number of items read. This number equals the number of bytes transferred only when size is 1.
So there is a difference between these two:
size_t n = fread (buffer, s, 1, fp);
size_t n = fread (buffer, 1, s, fp);
The first is reading up to one element of size s
so will only ever return zero or one. The second is reading up to s
elements of size one so can return a value of 0..s
inclusive.
The latter is the one you want to use if you want to read as many bytes at a time as you can fit in a buffer:
char buff[128];
size_t sz;
FILE *fp = fopen ("name.ima", "rb");
if (fp != NULL) {
while ((sz = fread (buff, 1, sizeof (buff), fp)) > 0)
doSomethingWith (buffer, sz);
fclose (fp);
}