What’s the sizeof That?

When writing a structure to a file, you need to ensure that you specify the proper structure size. The sizeof keyword is obviously the way you determine the size, but what exactly are you getting the size of?

For example, suppose you have a structure called record. Then you have an array of the structure record called database. You write an individual structure to disk by using the fwrite() statement:

fwrite(&database[3],sizeof(struct record),1,fptr);

&database[3] is the item that you’re writing to disk, presumably to the file represented by fptr. But the size of the item you’re writing to disk is based on the size of the structure, not the size of that one element. For example, the following statement is incorrect:

fwrite(&database[3],sizeof(database[3]),1,fptr);

Or even this:

fwrite(&database[3],sizeof(struct database[3]),1,fptr);

In either case the sizeof operator returns the size of the element you’re writing, not of the full structure. The two values could be different! Therefore, it’s best to always use the defined structure size when writing elements to a file.

A great tool to discover how information is written to disk is a file dumper. In Unix, you can use the hexdump utility to view raw bytes in a file. For writing a structure to a random access file, you should see the records evenly spread out within the file. Each record starts at a given offset. When you see that offset shift, then you know that the program is not writing data to the file in even chunks.

Leave a Reply