|
马上注册,结交更多好友,享用更多功能^_^
您需要 登录 才可以下载或查看,没有账号?立即注册
x
本帖最后由 18878977809 于 2021-2-27 11:19 编辑
- #include<stdio.h>
- #define SIZE 4
- struct student
- {
- char name[10];
- int num;
- int age;
- char addr[15];
- }stu[SIZE];
- void load();//将文件读取出来
- void save()//将从键盘输入的数据以二进制存储到磁盘文件中
- {
- FILE *fp;
- int i;
- if(!(fp=fopen("student_list","wb")))
- {
- printf("Cannot open the file!\n");
- return;
- }
- for(i=0;i<SIZE;i++)
- {
- if(fwrite(&stu[i],sizeof(struct student),1,fp)!=1)
- {
- printf("file write error!\n");
- fclose(fp);
- }
- }
- }
- void main()
- {
- int i;
- printf("please input the student's name,num,age and address:\n");
- for(i=0;i<SIZE;i++)
- {
- scanf("%s %d %d %s",stu[i].name,&stu[i].num,&stu[i].age,stu[i].addr);
- }
- save();
- load();
- }
- void load()
- {
- FILE *fp;
- int i;
- if(!(fp=fopen("student_list","rb+")))
- {
- printf("打开错误!\n");
- return;
- }
- for(i=0;i<SIZE;i++)
- {
- if(fread(&stu[i],sizeof(struct student),1,fp)!=1)//fread(&stu[i],sizeof(struct student),1,fp)
- {
- printf("file read error!\n");
- fclose(fp);
- }
- else
- {
- printf("%s %d %d %s\n",stu[i].name,stu[i].num,stu[i].age,stu[i].addr);
- }
- }
- }
- //试试在main中去掉下面这段代码,就正常了(前提student_list文件已建立)
- #if(0)
- printf("please input the student's name,num,age and address:\n");
- for(i=0;i<SIZE;i++)
- {
- scanf("%s %d %d %s",stu[i].name,&stu[i].num,&stu[i].age,stu[i].addr);
- }
- save();
- #endif
复制代码
为什么会这样子?
对应题目是小甲鱼老师09年老版的C语言62讲的课后习题 |
|