【发布时间】:2021-09-14 00:37:14
【问题描述】:
我有一个包含以下十六进制值的二进制文件。
用正确的代码读取这个二进制文件应该显示如下:
第一个图像中绿色突出显示的区域代表父亲、房间、吸引力、蛋糕的字段,分别输出值为 1,1,0,1。
我必须弄清楚我在下面编写的代码中使用什么数据类型为结构变量打印出 1,1,0,1。
我猜到 1101 来自十六进制“d”。但是,我不确定它是如何在 4 个不同的字段中打印出来的。
我知道我的问题与结构填充或位字段有关。但是,我仍然不确定我的代码和 fread 应该如何修改。
如果您能帮我解决这个问题或提供示例或相关阅读材料,我们将不胜感激。
#define MAX_HAT 9
#include<stdio.h>
#include<stdlib.h>
//struct variables
struct test
{
short int land;
float experience;
char boys;
short int angle;
double industry;
int thread;
long int shoe;
float kitty;
unsigned char price;
//not sure whether this is done correctly
unsigned int father: 1;
unsigned int room: 1;
unsigned int attraction: 1;
unsigned int cake: 1;
int foot;
char hat[MAX_HAT];
char nest;
float bean;
};
int main(int argc, char **argv)
{
struct test t1;
FILE *fp;
//Input Checking Error
if (argc < 2) {
fprintf(stderr, "Usage: %s input_file\n", argv[0]);
exit(1);
}
//binary file to open for reading
fp = fopen(argv[1], "rb");
//File Checking Error
if (fp == NULL){
fprintf(stderr, "Cannot open the file %s\n", argv[1]);
exit(1);
}
//Print out struct fields
printf("land, experience, boys, angle, industry, thread, shoe, kitty, price, father, room, attraction, cake, foot, hat, nest, bean \n");
//Allocate the values into the struct
while(fread(&t1.land, sizeof(t1.land), 1, fp) == 1)
{
fread(&t1.experience, sizeof(t1.experience), 1, fp);
fread(&t1.boys, sizeof(t1.boys), 1, fp);
fread(&t1.angle, sizeof(t1.angle), 1, fp);
fread(&t1.industry, sizeof(t1.industry), 1, fp);
fread(&t1.thread, sizeof(t1.thread), 1, fp);
fread(&t1.shoe, sizeof(t1.shoe), 1, fp);
fread(&t1.kitty, sizeof(t1.kitty), 1, fp);
fread(&t1.price, sizeof(t1.price), 1, fp);
fread(&t1.father, sizeof(t1.father), 1, fp);
fread(&t1.room, sizeof(t1.room), 1, fp);
fread(&t1.attraction, sizeof(t1.attraction), 1, fp);
fread(&t1.cake, sizeof(t1.cake), 1, fp);
fread(&t1.foot, sizeof(t1.foot), 1, fp);
fread(&t1.hat, sizeof(t1.hat), 1, fp);
fread(&t1.nest, sizeof(t1.nest), 1, fp);
fread(&t1.bean, sizeof(t1.bean), 1, fp);
//Print out the outputs
printf("%d, %f, %i, %i, %f, %d, %ld, %f, %u, %, %, %, %, %x, %s, %c, %f\n", t1.land, t1.experience, t1.boys, t1.angle, t1.industry, t1.thread, t1.shoe, t1.kitty, t1.price, t1.father, t1.room, t1.attraction, t1.cake,t1.foot, t1.hat, t1.nest, t1.bean);
}
//close the file
fclose(fp);
return 0;
}
【问题讨论】:
-
可能是位域?
-
@kaylum 我需要对我的代码进行更改吗?
-
fread (&t1, sizeof t1, 1, fp)不起作用吗?现在数据应该被序列化,bur 对于许多学习读/写结构数据的人来说,一次读取一个结构(只要它是由相同架构上的相同编译器编写的)通常是预期的。您可以使用多个fread()调用,但如果存在填充,您将不会阅读您认为正在阅读的内容。
标签: c fread bit-fields