C fread() 一个结构体

标签 c struct fread

我工作了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/

相关文章:

c - C 中的 fread 实际上是如何工作的?

c - gcc: __fread_chk_warn 警告

c - &address + sizeof(type) 和 &address + 1 有什么区别?

C -> 大型机上的 COBOL 跨语言通信

涉及输出计时持续时间的 C++ 错误

c - 从csv文件中读取错误的数字 '\n'

c - 为什么不是 scanf ("%*[^\n]\n");和 scanf ("%*[^\n]%*c");清除挂起的换行符?

c - 为什么long long int不会溢出?

c - 可能是内存问题还是其他什么问题?

c# - 将 C 结构从 dll 转换为 C#