|
|
马上注册,结交更多好友,享用更多功能^_^
您需要 登录 才可以下载或查看,没有账号?立即注册
x
关于student-list的问题。先使用sava()函数从键盘写入数据,并储存到文件student-list中,然后再用load()函数读出,显示到屏幕上。小甲鱼老师给的答案是将save()和load()做成两个文件,我想把这两个文件合并成一个文件。代码如下:
- #include <stdio.h>
- #define SIZE 2
- struct student
- {
- char name[10];
- int num;
- int age;
- char addr[15];
- }stu[SIZE],stud[SIZE];
- void save()
- {
- FILE *fp;
- int i;
-
- if( !(fp = fopen("D:\\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 load()
- {
- FILE *fp;
- int i;
-
- if( !(fp = fopen("D:\\student-list", "r")))
- {
- printf("Cannot open the file!\n");
- return;
- }
- printf(" name num age address\n\n");
-
- for( i=0; i < SIZE; i++ )
- {
- fread(&stud[i], sizeof(struct student), 1, fp);
- printf("%10s %5d %5d %10s\n", stud[i].name, stud[i].num, stud[i].age, stud[i].addr);
- }
-
- 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();
- }
复制代码 首先将SIZE改成了2,方便调试,再次为了体验到是将数据从结构体写入文件,再从文件中读取出来的,我又设置了一个结构体数组stud[2]作为从文件中读取的承载体(因为如果继续使用stu[2],那即便没有load()函数,不从文件中读取,结果还是对的)。但是我这样调试后,结果却只有0字符,求各位鱼友一起探讨啊!
|
|