我工作了2个小时,我在Google上搜索,但没有找到答案,所以我问你!希望有人的帮助。当我尝试打印我的结构时,我只得到 1 个空结构(结构已正确创建、填充并存储在文件中)
我的结构是这样的:
typedef struct
{
int serial_number;
char name [20];
char surname [20];
char sex[1];
int dd;
int mm;
int yyyy;
} Person;
这是 print_file 函数
int print_file()
{
FILE *f;
f = fopen("civil_registry.dat", "rb");
if (!f)
{
error("Error on opening file, should be missing!");
return 1;
}
Person *tmp;
tmp = malloc(sizeof(Person));
fseek(f, 0, SEEK_END);
int length_of_file = ftell(f);
while(length_of_file)
{
fread(tmp, sizeof(Person), 1, f);
print(tmp);
length_of_file = length_of_file - 64;
}
fclose(f);
return 0;
}
这里打印功能可以正常工作(我认为):
int print(Person *tmp)
{
printf("\n\nSerial Number: %i", tmp->serial_number);
printf("\nName: %s", tmp->name);
printf("\nSurname: %s", tmp->surname);
printf("\nSex: %s", tmp->sex);
printf("\nDay: %i", tmp->dd);
printf("\nMonth: %i", tmp->mm);
printf("\nYear: %i", tmp->yyyy);
return 0;
}
最佳答案
您的代码中存在未定义的行为。
char sex[1] ;
并在函数print
中 -
printf("\nSex: %s", tmp->sex); // %s would expect a null terminated string
如果您在 sex
中输入字符,则 '\0'
中没有空格。
因此将其大小增加到 char sex[2]
。
关于C fread() 一个结构体,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33242852/