关于C语言文件输入

来源:百度知道 编辑:UC知道 时间:2024/05/27 15:19:57
#include<stdio.h>
struct student
{
char name[10];
int age;
char sex;
int ID;
float GPA;
}stu1[5];

void main()
{
FILE *fp1,*fp2;
int i=0;
fp1=fopen("c:\\1.txt","r");
if(fp1==NULL)
{
printf("Fail to open the infile\n");
}
fp2=fopen("c:\\2.txt","wb");
if(fp2==NULL)
{
printf("fail to open the outfile\n");
}
while(fscanf(fp1,"%s%d%c%d%f",stu1[i].name,&stu1[i].age,&stu1[i].sex,&stu1[i].ID,&stu1[i].GPA)!=EOF)
{
if(stu1[i].age>1987)
fwrite(&stu1[i],sizeof(student),1,fp2);
i++;
}
fclose(fp1);
fclose(fp2);
}
其中1.txt为:
Lee 1988 M 27 3.14
Marry 1987 F 33 3.41
Barton 1989 M 12 3.22
Jacky 1986 M 7 3.55
Lucy 1990 F 8 3.88
请问程序哪里有错(拜托了,小弟实在不太明白)

改成这样:
#include<stdio.h>
#include<stdlib.h>

typedef struct student
{
char name[10];
int age;
char sex;
int ID;
float GPA;
} student;

student stu1[5];

void main()
{
FILE *fp1,*fp2;
int i=0;
char tname[10],tsex;
int tage,tGPA,tID;

fp1=fopen("1.txt","r");
if(fp1==NULL)
{
printf("Fail to open the infile\n");
}
fp2=fopen("2.txt","wb");
if(fp2==NULL)
{
printf("fail to open the outfile\n");
}

while(1==1)
{
if (fscanf(fp1,"%s %d %s %d %f",
tname,&tage,&tsex,&tID,&tGPA)==EOF) break;
strcpy(stu1[i].name,tname);
stu1[i].age=tage;
stu1[i].sex=tsex;
stu1[i].ID=tID;
stu1[i].GPA=tGPA;

if(stu1[i].age>1987)
fwrite(&stu1[i],sizeof(student),1,fp2);
i++;