views:

243

answers:

2

Hi All,

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?

Regards, darkie

+5  A: 

fseek just moves the position pointer of the file stream; once you've moved the position pointer, you need to call fread to actually read bytes from the file.

However, if you've already read the first eight bytes from the file using fread, the position pointer is left pointing to the ninth byte (assuming no errors happen and the file is at least nine bytes long, of course). When you call fread, it advances the position pointer by the number of bytes that are read. You don't have to call fseek to move it.

James McNellis
Thanks I got it. Also, can you tell me how I can skip a specific number of bytes? Currently, I am only reading the number of bytes I want to skip in a byte array to move the cursor. Am wondering if there is any library that does perform the same function.
darkie15
@darkie15: Then you want to use `SEEK_CUR`, not `SEEK_SET`, which tells `fseek` to use the offset relative to the current position, instead of the start of the file.
Jefromi
thanks jefromi !
darkie15
+2  A: 

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)

Eli Bendersky
that is very illustrative .. thank you very much eli !!
darkie15