I am having following issue with reading binary file in C.
I have read the first 8 bytes of a binary file. Now I need to start reading from the 9th byte. Following is the code:
fseek(inputFile, 2*sizeof(int), SEEK_SET);
However, when I print the contents of the array where I store the retrieved values, it still shows me the first 8 bytes which is not what I need.
Can anyone please help me out with this?
Assuming:
FILE* file = fopen(FILENAME, "rb");
char buf[8];
You can read the first 8 bytes and then the next 8 bytes:
/* Read first 8 bytes */
fread(buf, 1, 8, file);
/* Read next 8 bytes */
fread(buf, 1, 8, file);
Or skip the first 8 bytes with fseek
and read the next 8 bytes (8 .. 15 inclusive, if counting first byte in file as 0):
/* Skip first 8 bytes */
fseek(file, 8, SEEK_SET);
/* Read next 8 bytes */
fread(buf, 1, 8, file);
The key to understand this is that the C library functions keep the current position in the file for you automatically. fread
moves it when it performs the reading operation, so the next fread
will start right after the previous has finished. fseek
just moves it without reading.
P.S.: My code here reads bytes as your question asked. (Size 1 supplied as the second argument to fread
)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With