【发布时间】:2017-01-26 03:29:24
【问题描述】:
我正在使用以下代码从二进制文件中提取结构成员。
我想知道为什么这会打印多次?当只有一个 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];
}
【问题讨论】:
-
为什么不确定这是 C 还是 C++?你知道你是怎么编译的……对吧?
-
我可以同时使用这两个...
-
2906 远大于 4 个整数的大小——通常是 16 个字节——因此不止一个结构
-
我想你已经回答了这个问题
-
@Ke。
Sorry there is one large chunk at the end I forgot to include in the struct那你应该更新你的Q,以免读者对大小不匹配感到困惑。