首页 > 解决方案 > 如何将 fread() 2 个结构放在一起 C

问题描述

如何fread()在 1 行中显示 2 个语句。

这是我的代码的一部分:

FILE *fp;
fp = fopen("hello", "rb");

struct clientName NAME;
struct clientAge AGE;

system("cls");
if(fp == NULL){
printf("ERROR");
getch();
}
else{
printf("NAME\t\tAGE\n");
printf("-----------------------------------------\n");
while((fread((char *)&NAME, sizeof(struct clientName), 1, fp))==1){
    printf("%s", NAME.name);    
    while((fread((char *)&AGE, sizeof(struct clientAge), 1, fp))==1){
        printf("\t\t%d", AGE.age);
    }
}

当有 1 组数据时,格式正确。但是当有 2 组或更多组数据时,它开始变得混乱。我对 C 中的文件处理真的很陌生。谢谢!

标签: cfile-handling

解决方案


假设您的文本格式如下。

  name1
  age1
  name2
  age2  

在这种情况下,您需要的是。

  while((fread((char *)&NAME, sizeof(struct clientName), 1, fp))==1 &&
           (fread((char *)&AGE, sizeof(struct clientAge), 1, fp))==1){
             printf("%s", NAME.name);    
             printf("\t\t%d", AGE.age);
     }

推荐阅读