gpt4 book ai didi

c - 带有位域和 char * 的 fwrite/fread 结构

转载 作者:行者123 更新时间:2023-11-30 14:54:45 25 4
gpt4 key购买 nike

我正在测试一个自定义结构,其中有位字段和一个 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?

最佳答案

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

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);

关于c - 带有位域和 char * 的 fwrite/fread 结构,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46513027/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com