总体写得不错,问题出在你的
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
结果:
![](https://video.ask-data.xyz/img.php?b=https://iknow-pic.cdn.bcebos.com/562c11dfa9ec8a13b9c22c80f503918fa1ecc0f2?x-bce-process=image%2Fresize%2Cm_lfit%2Cw_600%2Ch_800%2Climit_1%2Fquality%2Cq_85%2Fformat%2Cf_auto)
text.txt中内容就是output.txt中的内容
![](https://video.ask-data.xyz/img.php?b=https://iknow-pic.cdn.bcebos.com/838ba61ea8d3fd1f236bd85a324e251f95ca5f6b?x-bce-process=image%2Fresize%2Cm_lfit%2Cw_600%2Ch_800%2Climit_1%2Fquality%2Cq_85%2Fformat%2Cf_auto)