[英]fwrite/fread struct with bitfields and char *
I am testing a custom structure where there is bitfield and a unsigned char * (that will be allocated later). 我正在测试一个自定义结构,其中有位字段和一个无符号char *(将在以后分配)。
Here is the structure : 这是结构:
struct test {
unsigned int field1 : 1;
unsigned int field2 : 15;
unsigned int field3 : 32;
unsigned int dataLength : 16;
unsigned char * data;
}
The problem is when I tried to save this struct inside a file in hex. 问题是当我尝试将此结构保存为十六进制文件时。
For example : 例如 :
int writeStruct(struct test *ptr, FILE *f) {
// for data, suppose I know the length by dataLength :
// this throw me : cannot take adress of bit field
int count;
count = fwrite( &(ptr->field2), sizeof(unsigned int), 1, f);
// this throw me : makes pointer to integer without a cast
count = fwrite( ptr->field2, sizeof(unsigned int), 1, f);
// same for length
count = fwrite( htons(ptr->data) , ptr->dataLength, 1,f);
// so , how to do that ?
}
The same problem goes to fread : 同样,fread也有问题:
int readAnStructFromFile(struct test *ptr, FILE *f) {
// probably wrong
fread(ptr->field1, sizeof(unsigned int), 1, f);
}
So , how can I write/read struct like this ? 那么,我怎么能这样写/读结构呢?
Thanks for your help 谢谢你的帮助
PS for fread, this could work if there wasn't these bitfields: How to fread() structs? PS for fread,如果没有这些位字段,则可以使用: 如何fread()结构?
there is no way to get an address of a bitfield. 无法获得位域的地址。 The usual way to handle it is to either use a temporary variable on read/write sides or just to save the whole struct as a single entity.
处理它的通常方法是在读/写侧使用临时变量,或者仅将整个结构保存为单个实体。 With temp vars it looks like the following:
使用temp var时,其外观如下所示:
int count;
int field2 = ptr->field2;
count = fwrite( &field2, sizeof(unsigned int), 1, f);
...
int field1;
fread(&field1, sizeof(unsigned int), 1, f);
ptr->field1 = field1;
or for the whole struct: 或对于整个结构:
count = fwrite( ptr, sizeof(struct test), 1, f);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.