鱼C论坛

 找回密码
 立即注册
查看: 1844|回复: 2

文件操作

[复制链接]
发表于 2021-2-27 10:57:25 | 显示全部楼层 |阅读模式

马上注册,结交更多好友,享用更多功能^_^

您需要 登录 才可以下载或查看,没有账号?立即注册

x
本帖最后由 18878977809 于 2021-2-27 11:19 编辑
  1. #include<stdio.h>
  2. #define SIZE 4
  3. struct student
  4. {
  5.         char name[10];
  6.         int num;
  7.         int age;
  8.         char addr[15];
  9. }stu[SIZE];

  10. void load();//将文件读取出来

  11. void save()//将从键盘输入的数据以二进制存储到磁盘文件中
  12. {
  13.         FILE *fp;
  14.         int i;

  15.         if(!(fp=fopen("student_list","wb")))
  16.         {
  17.                 printf("Cannot open the file!\n");
  18.                 return;
  19.         }
  20.         for(i=0;i<SIZE;i++)
  21.         {
  22.       if(fwrite(&stu[i],sizeof(struct student),1,fp)!=1)
  23.           {
  24.          printf("file write error!\n");
  25.                  fclose(fp);
  26.           }
  27.         }
  28. }

  29. void main()
  30. {
  31.         int i;
  32.              printf("please input the student's name,num,age and address:\n");
  33.         for(i=0;i<SIZE;i++)
  34.         {
  35.       scanf("%s %d %d %s",stu[i].name,&stu[i].num,&stu[i].age,stu[i].addr);
  36.         }

  37.         save();
  38.         load();
  39. }

  40. void load()
  41. {
  42.         FILE *fp;
  43.         int i;
  44.     if(!(fp=fopen("student_list","rb+")))
  45.         {
  46.                 printf("打开错误!\n");
  47.                 return;
  48.         }
  49.         for(i=0;i<SIZE;i++)
  50.         {
  51.                 if(fread(&stu[i],sizeof(struct student),1,fp)!=1)//fread(&stu[i],sizeof(struct student),1,fp)
  52.                 {
  53.            printf("file read error!\n");
  54.                   fclose(fp);
  55.                 }
  56.                 else
  57.                 {
  58.             printf("%s %d %d %s\n",stu[i].name,stu[i].num,stu[i].age,stu[i].addr);
  59.                 }
  60.         }

  61. }

  62. //试试在main中去掉下面这段代码,就正常了(前提student_list文件已建立)
  63. #if(0)
  64.         printf("please input the student's name,num,age and address:\n");
  65.         for(i=0;i<SIZE;i++)
  66.         {
  67.       scanf("%s %d %d %s",stu[i].name,&stu[i].num,&stu[i].age,stu[i].addr);
  68.         }

  69.         save();
  70. #endif
复制代码


为什么会这样子?
对应题目是小甲鱼老师09年老版的C语言62讲的课后习题
小甲鱼最新课程 -> https://ilovefishc.com
回复

使用道具 举报

 楼主| 发表于 2021-2-27 11:47:10 | 显示全部楼层
找出问题了,在save函数中没有断开文件指针fp与文件的关联
小甲鱼最新课程 -> https://ilovefishc.com
回复 支持 反对

使用道具 举报

发表于 2021-2-27 12:57:46 | 显示全部楼层
!,好一个自问自答
小甲鱼最新课程 -> https://ilovefishc.com
回复 支持 反对

使用道具 举报

您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

小黑屋|手机版|Archiver|鱼C工作室 ( 粤ICP备18085999号-1 | 粤公网安备 44051102000585号)

GMT+8, 2025-4-28 16:16

Powered by Discuz! X3.4

© 2001-2023 Discuz! Team.

快速回复 返回顶部 返回列表