简体   繁体   中英

fwrite() and fread() parts of a struct into binary file

My binary file is divided into blocks. Now I want to write a struct to my binary file. If the size of my struct is larger than the size of a block, I'm thinking of splitting the struct into parts, then write each part to a block (Those blocks do not need to be contiguous).

For example, I divide my binary file into blocks of size 4 bytes. The size of my struct is 9 bytes. Then I split my struct into 3 parts (4 bytes, 4 bytes, and 1 byte). And I'm going to write part 1 (4 bytes) to 1st block, part 2 (4 bytes) to 3rd block, and part 3 (1 byte) to 6th block.

So if I use fwrite(str , 4 , 1 , file) , I can write the part 1 to 1st block. But how about the other parts?

Also, if I want to read my struct from my binary file as my struct is split into 3 parts as above. How can I read each part and combine them into a complete struct using fread()?

Is this idea possible?

unsigned char is guaranteed to have no padding bits, and it's size is by defintion 1, so a data object of any other type can be copied as sizeof(the object or the type) unsigned chars. You can't compare two objects as two unsigned char arrays though, because the larger type may have padding (don't care) bits which could differ in the two objects.

Writing:

unsigned char *ptr;

ptr = (unsigned char *) &myStruct;
fwrite(ptr, 1, 4, myStream);
ptr += 4;
fwrite(ptr, 1, 4, myStream);
ptr += 4;
fwrite(ptr, 1, 1, myStream);

Reading:

unsigned char *ptr;

ptr = (unsigned char *) &myStruct;
fread(ptr, 1, 4, myStream);
ptr += 4;
fread(ptr, 1, 4, myStream);
ptr += 4;
fread(ptr, 1, 1, myStream);

It's probably a good idea to read/write 4 elements of size 1, instead of 1 object of size 4. The latter could screw up align restrictments, I think.

If you want, skip the ptr variable and cast on-the-fly:

fwrite(&myStruct, 1, 4, myStream);
fwrite((unsigned char *) &myStruct + 4, 1, 4, myStream);
fwrite((unsigned char *) &myStruct + 8, 1, 1, myStream);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM