带有位域和字符*的fwrite / fread结构

时间:2017-10-01 13:49:54

标签: c struct fwrite bit-fields

我正在测试一个自定义结构,其中有bitfield和unsigned char *(将在稍后分配)。

这是结构:

struct test {
  unsigned int field1 : 1;
  unsigned int field2 : 15;
  unsigned int field3 : 32;
  unsigned int dataLength : 16;
  unsigned char * data;
} 

问题是当我尝试将此结构保存在十六进制文件中时。

例如:

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 ?
}

同样的问题是fread:

int readAnStructFromFile(struct test *ptr, FILE *f) {
   // probably wrong
   fread(ptr->field1, sizeof(unsigned int), 1, f);
}

那么,我怎么能像这样写/读结构?

感谢您的帮助

PS for fread,如果没有这些位域,这可能会有效:How to fread() structs?

1 个答案:

答案 0 :(得分:1)

无法获取位域的地址。处理它的常用方法是在读/写端使用临时变量,或者只是将整个结构保存为单个实体。对于临时变量,它看起来如下:

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;

或整个结构:

count = fwrite( ptr, sizeof(struct test), 1, f);