关于文件的读写问题
发布网友
发布时间:2022-04-26 00:29
我来回答
共1个回答
热心网友
时间:2023-10-24 19:26
我大致看了一下,找到一个很明显到错误!!!
void input()
{
int i;
printf("please ipiut the information of the students:\n");
for(i=0;i<M;i++)
scanf("%s%d%d", &stu[i].name, &stu[i].num, &stu[i].score);//把M换成i,因为你到循环变量是i
printf("the information has been inported.\n\n");
}
void load(char name[])
{
FILE *p;
struct student stu1[M];
int i;
p=fopen( name,"wb");
printf("the information of the file is :\n");
fread( stu1, sizeof(struct student), M, p);
for (i=0;i<M;i++)
printf("%s%d%d\n", stu1[i].name, stu1[i].num, stu1[i].score); //这里输出到时候也一样
fclose (p);
}
补充回答:
void load(char name[])
{
FILE *p;
struct student stu1[M];
int i;
p=fopen( name,"wb");//你的这个函数是读取文件数据,打开方式应为"rb","wb"是写的方式
printf("the information of the file is :\n");
fread( stu1, sizeof(struct student), M, p);
for (i=0;i<M;i++)
printf("%s%d%d\n", stu1[M].name, stu1[M].num, stu1[M].score);
fclose (p);
}
还有你的这个程序有很多地方容易导致错误!比如说scanf("%s%d%d", &stu[M].name, &stu[M].num, &stu[M].score); name是字符数组的数组名,本身就代表该数组的首地址,没必要再取其地址了!虽然你这样写运行时没有问题,但难保你能用的顺利!fread和fwrite函数处理数据的效率比较高,但是这两个函数除非你用的熟练,否则很容易就出错!而且fwrite函数写入的是二进制数据,没办法核对你写入文件的数据是否正确!所以对于小程序来说尽量使用fscanf和fprinf两个函数处理数据,易于检查!
程序我帮你改好了,你自己试一下!
#include "stdio.h"
#include "conio.h"
#define M 3
struct student
{
char name [20];
int num;
int score;
} stu[M];
void main()
{
void input();
void save(char name[]);
void load(char name[]);
char name[20];
input();
printf("please input the name of the saved file:");
scanf("%s",name);
save(name);
load(name);
getch();
}
void input()
{
int i;
printf("please ipiut the information of the students:\n");
for(i=0;i<M;i++)
scanf("%s%d%d", stu[i].name, &stu[i].num, &stu[i].score);
printf("the information has been inported.\n\n");
}
void save(char name[])
{
int i;
FILE *p;
p=fopen( name,"wb");
fwrite( stu, sizeof(struct student), M, p);
printf("the file has been saved.\n\n");
fclose(p);
}
void load(char name[])
{
FILE *p;
struct student stu1[M];
int i;
p=fopen( name,"rb");
printf("the information of the file is :\n");
fread( stu1, sizeof(struct student), M, p);
for (i=0;i<M;i++)
printf("%4s%4d%4d\n", stu1[i].name, stu1[i].num, stu1[i].score);
fclose (p);
}