|
马上注册,结交更多好友,享用更多功能^_^
您需要 登录 才可以下载或查看,没有账号?立即注册
x
本帖最后由 小甲鱼的铁粉 于 2020-10-4 14:29 编辑
将这个文件内容输出时会有重复,我输入的是这样的
- 111 qqq 100 100 100
- 222 www 99 99 99
- 333 eee 98 98 98
复制代码
读取文件并输出是这样的
- 111 qqq 100 100 100
- 222 www 99 99 99
- 333 eee 98 98 98
- 333 eee 98 98 98
复制代码
也就是最后一个学生的成绩读取重复了一次,麻烦鱼油们找一下问题吧
- #include<stdio.h>
- #include<stdlib.h>
- struct student
- {
- char stu_num[13];//学号
- char name[20];//姓名
- int chinese;
- int math;
- int english;
- int sum;
- }Stu;
- void CreateManagementAystem()
- {
- FILE *fp;
- if((fp = fopen("C:/Users/86188/Desktop/vscode_c/CurriculumDesgin/StudentsData.txt","wb")) == NULL)
- {
- printf("Open error!");
- exit(0);
- }
- int N;//有多少个学生
- printf("Please input the number of students:");
- scanf("%d",&N);
- for(int i = 0; i < N; i++)
- {
- printf("Please input the %dth student\n",i+1);
- //先将学生数据放入结构体Stu,再一起写入文件
- scanf("%s%s%d%d%d",Stu.stu_num, Stu.name, &Stu.chinese, &Stu.math, &Stu.english);
- Stu.sum = Stu.chinese + Stu.math + Stu.english;
- fwrite(&Stu, sizeof(Stu), 1, fp);
- }
- fclose(fp);
- }
- void PrintGrades()
- {
- FILE *fp;
- if((fp = fopen("C:/Users/86188/Desktop/vscode_c/CurriculumDesgin/StudentsData.txt","rb")) == NULL)
- {
- printf("Open error!");
- exit(EXIT_FAILURE);
- }
- [color=Red]//读取数据并输出,这里出问题了[/color]
- while(!feof(fp))
- {
- fread(&Stu, sizeof(Stu), 1, fp);
- printf("%s %s %d %d %d %d\n", Stu.stu_num, Stu.name, Stu.chinese, Stu.math, Stu.english, Stu.sum);
- }
- fclose(fp);
- }
- int main()
- {
- CreateManagementAystem();
- PrintGrades();
- system("pause");
- return 0;
- }
复制代码
eof(fp)有两个返回值:如果遇到文件结束,函数feof(fp)的值为1,否则为0。当读到文件末尾时,文件指针并没有超出文件,所以会多读一次。
我在外地,所带的手提电脑上的 DEV-C++ 编译软件有问题,没法测试后,给出具体的运行正常的程序给你,你自己修改你的程序后运行测试
解决办法:
fseek(fp1,0,2); //文件末
w=ftell(fp1); // 文件末指针的值
fseek(fp1,0,0); //文件首
while(w != ftell(fp1)) //循环
|
-
|