4

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?

2 Answers 2

11

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)

Sign up to request clarification or add additional context in comments.

1 Comment

Note: if you wish to read 8, skip 8, read 8 use SEEK_CUR, like so: fread(buf, 1, 8, file);fseek(file, 8, SEEK_CUR);fread(buf, 1, 8, file);
10

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.

2 Comments

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: 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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.