Search code examples
cbinaryfilesfseek

C Binary File Reading: How many bytes should I move?


Suppose I have a program that works with binary files in C language.

Suppose I have 8 objects (each object is a struct record type) in this binary file, and I have read the first 3 objects of the 8. (By reading 3 objects of the 8 I mean I have read it and store them into an array)

I know in order to read later content of the binary file, I have to use fseek call to achieve this goal. What I feel confused is this, suppose I want to read the 4th object of the 8, how many bytes/objects should I move/skip using fseek call?

Should I call

fseek(fp, sizeof(struct record) * 3, SEEK_SET);

or

fseek(fp, sizeof(struct record) * 4, SEEK_SET);

Solution

  • it's usually best to write these things down to get a sense of how the memory mapping works, so let's try and represent the file (assuming each struct is 4 bytes in size):

    byte:   |A-0|A-1|A-2|A-3|B-0|B-1|B-2|B-3|C-0|C-1|C-2|C-3|D-0|D-1|D-2|D-3|E....
            ----------------------------------------------------------------------
    struct: | struct A      |struct B       |struct C       |struct D       |s...
            ----------------------------------------------------------------------
    address:0   1   2   3   4   5   6   7   8   9  10   11  12  13  14  15  16
    

    as you can see from the visual representation, the file is 0-based indexed i.e. the first struct is located at address 0 (sizeof(struct record) * 0) the second is located at address 4 (sizeof(struct record) *1) and so on...

    from here one can derive for the nth element offset = ( sizeof(struct record) * ( n - 1) )

    hope it makes it clearer...