鱼C论坛

 找回密码
 立即注册
查看: 3931|回复: 1

C语言视频63讲homework的问题

[复制链接]
发表于 2012-12-9 12:14:05 | 显示全部楼层 |阅读模式

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

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

x
关于student-list的问题。先使用sava()函数从键盘写入数据,并储存到文件student-list中,然后再用load()函数读出,显示到屏幕上。小甲鱼老师给的答案是将save()和load()做成两个文件,我想把这两个文件合并成一个文件。代码如下:
  1. #include <stdio.h>
  2. #define SIZE 2
  3. struct student
  4. {
  5.         char name[10];
  6.         int num;
  7.         int age;
  8.         char addr[15];
  9. }stu[SIZE],stud[SIZE];

  10. void save()
  11. {
  12.         FILE *fp;
  13.         int i;
  14.        
  15.         if( !(fp = fopen("D:\\student-list", "wb")))
  16.         {
  17.                 printf("Cannot open the file!\n");
  18.                 return;
  19.         }
  20.        
  21.         for( i=0; i < SIZE; i++ )
  22.         {
  23.                 if( fwrite(&stu[i], sizeof(struct student), 1, fp) != 1 )
  24.                 {
  25.                         printf("File write error!\n");
  26.                         fclose(fp);
  27.                 }
  28.         }
  29. }

  30. void load()
  31. {
  32.         FILE *fp;
  33.         int i;
  34.        
  35.         if( !(fp = fopen("D:\\student-list", "r")))
  36.         {
  37.                 printf("Cannot open the file!\n");
  38.                 return;
  39.         }
  40.         printf("      name   num   age     address\n\n");
  41.        
  42.         for( i=0; i < SIZE; i++ )
  43.         {
  44.                 fread(&stud[i], sizeof(struct student), 1, fp);     
  45.                 printf("%10s %5d %5d %10s\n", stud[i].name, stud[i].num, stud[i].age, stud[i].addr);
  46.         }
  47.        
  48.         fclose(fp);
  49. }
  50. void main()
  51. {
  52.         int i;
  53.        
  54.         printf("Please input the student's name, num, age and address: \n");
  55.         for( i=0; i < SIZE; i++ )
  56.         {
  57.                 scanf("%s %d %d %s", stu[i].name, &stu[i].num, &stu[i].age, &stu[i].addr);
  58.         }
  59.        
  60.         save();
  61.         load();
  62. }
复制代码
首先将SIZE改成了2,方便调试,再次为了体验到是将数据从结构体写入文件,再从文件中读取出来的,我又设置了一个结构体数组stud[2]作为从文件中读取的承载体(因为如果继续使用stu[2],那即便没有load()函数,不从文件中读取,结果还是对的)。但是我这样调试后,结果却只有0字符,求各位鱼友一起探讨啊!

小甲鱼最新课程 -> https://ilovefishc.com
发表于 2013-5-16 14:43:45 | 显示全部楼层
强烈支持楼主ing……
小甲鱼最新课程 -> https://ilovefishc.com
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

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

GMT+8, 2025-11-16 18:51

Powered by Discuz! X3.4

© 2001-2023 Discuz! Team.

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