69,369
社区成员
发帖
与我相关
我的任务
分享
#include<stdio.h>
#include <stdlib.h>
#include <string.h>
#include <errno.h>
typedef struct data
{
char xuehao[12];
char xingming[6];
int math;
int wuli;
int yuwen;
int huaxue;
}DA;
int main()
{
DA student[50];
DA student1[50];
int i=0;
FILE *fp = fopen("D:\\zuoye\\stu.txt","r");
if (!fp) {
fprintf(stderr, "Open file error: %s\n", strerror(errno));
exit(0);
}
while(!feof(fp))
{
fscanf(fp,"%s%s%d%d%d%d\n",
student[i].xuehao,
student[i].xingming,
&student[i].math,
&student[i].wuli,
&student[i].yuwen,
&student[i].huaxue);
i++;
}
//打印信息
for(i=0;i<30;i++) {
printf("%s %s %d %d %d %d\n",
student[i].xuehao,
student[i].xingming,
student[i].math,
student[i].wuli,
student[i].yuwen,
student[i].huaxue);
}
fclose(fp);
FILE *fp1 = fopen("D:\\zuoye\\stu.dat","w");
if (!fp1) {
fprintf(stderr, "Open file error: %s\n", strerror(errno));
exit(0);
}
/*
for(i=0;i<30;i++)
fwrite(&student[i], sizeof(DA), 1, fp1);
*/
fwrite(student, sizeof(DA), 30, fp1);
fclose(fp1);
FILE *fp2 = fopen("D:\\zouye\\stu.dat","r");
if (!fp2) {
fprintf(stderr, "Open file error: %s\n", strerror(errno));
exit(0);
}
for(i=0;i<30;i++)
{
fread(&student1[i],sizeof(DA),1,fp2);
printf("%s %s %d %d %d %d\n",
student1[i].xuehao,
student1[i].xingming,
student1[i].math,
student1[i].wuli,
student1[i].yuwen,
student1[i].huaxue);
}
fclose(fp2);
}
参考一下吧
有两个地方需要注意:
第一个地方,fscanf读,如果你的txt文件是每个学生信息占一行,那么fscanf读取时注意加'\n';
第二个地方,也是主要的错误所在。fwrite没问题,一次性写了30个学生信息到文件中,但是读的时候有问题了,因为不是一次读30个学生信息,而是一次读一个学生信息,因此fread的第一个参数应该是&student1[i],而不是student1.
建议自己思考一下fread的第一个参数应该是什么