C语言 怎么把文件中的信息储存到结构体数组中

要把这个文件中的数据保存到结构体数组中

我是这么写的

输出为什么是这个

总体写得不错,问题出在你的

fscanf和fprintf函数参数传递错误了

#include "stdio.h"
#include "stdlib.h"
struct s
{
  int id;
  char name[10];
  int co1;
  int co2;
  int co3;
  int co4;
};
int main()
{
   int i=0,count;
   struct s st[10];
   char fname[10],ch;
   FILE *infile,*outfile;
   printf("please input data file name:\n");
   scanf("%s",fname);
   infile=fopen(fname,"r");
   outfile=fopen("output.txt","w");
   if(infile==NULL)
   {
     printf("\nFailed to open the file");
 exit(1);
   }
   fscanf(infile,"%d",&count);
   while(i<count)
   {
     fscanf(infile,"%d %s %d %d %d %d\n",&(st[i].id),st[i].name,&(st[i].co1),&(st[i].co2),&(st[i].co3),&(st[i].co4));
 fprintf(outfile,"%d %s %d %d %d %d\n",st[i].id,st[i].name,st[i].co1,st[i].co2,st[i].co3,st[i].co4);
     i++;
   }
   fclose(infile);
   fclose(outfile);
}

首先,你的name是结构体中的字符数组,fscanf要传入的应该是存储字符的地址,所以直接是数组名name就行


第二,fprintf你要写入文件的数据,应该是真正的数据本身,不是数据的地址,所以应该将变量前的取地址符全去掉就好,


第三,注意加好换行符\n


结果:

text.txt中内容就是output.txt中的内容

温馨提示:答案为网友推荐,仅供参考
第1个回答  2013-12-29
你用了地址运算符&,输出的应该是各个数据的存储地址。
相似回答