Reading Binary file in C
I开发者_StackOverflow 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
)
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.
精彩评论