我使用以下代码从二进制文件中提取结构成员。
我想知道为什么会打印多次?当文件中只有一个 ID 记录并且只有一个结构体时。我只需要访问该成员,最好的方法是什么?
我不太明白while循环是做什么的?它是否测试文件是否打开并在该点之前返回 1?
为什么在 while 循环中使用 fread?
fread是否需要设置为struct成员的具体大小?
printf 语句是否读取二进制并输出 int?
FILE *p;
struct myStruct x;
p=fopen("myfile","rb");
while(1) {
size_t n = fread(&x, sizeof(x), 1, p);
if (n == 0) {
break;
}
printf("\n\nID:%d", x.ID); // Use matching specifier
fflush(stdout); // Insure output occurs promptly
}
fclose(p);
return 0;
结构如下所示:
struct myStruct
{
int cm;
int bytes;
int ID;
int version;
char chunk[1];
}
最佳答案
并不是真正的答案,而是回答评论。
就这么做
FILE *p = fopen("myfile","rb");
struct myStruct x;
size_t n = fread(&x, sizeof(x), 1, p);
if (n != 1) {
// Some error message
} else {
printf("\n\nID:%d\n", x.ID);
}
...Do as you wish with the rest of the file
关于c++ - C、C++ 从二进制文件中提取结构成员,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39556266/