Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reading Binary file in C

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?

like image 497
name_masked Avatar asked Nov 29 '22 18:11

name_masked


1 Answers

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)

like image 166
Eli Bendersky Avatar answered Dec 04 '22 22:12

Eli Bendersky