修改这段代码 void in() { int i, m = 0; char ch[2]; FILE* fp; if ((fp = fopen("d:/学生系统/student.txt", "ab+")) == NULL) { printf("can not open\n"); return; } while (!feof(fp)) { if (fread(&stu[m], LEN, 1, fp) == 1) m++; } fclose(fp); if (m == 0) printf("No record!\n"); else { system("cls"); show(); } if ((fp = fopen("d:/学生系统/student.txt", "wb")) == NULL) { printf("can not open\n"); return; } for (i = 0; i < m; i++) fwrite(&stu[i], LEN, 1, fp); printf("please input(y/n):"); scanf("%s", ch); while (strcmp(ch, "Y") == 0 || strcmp(ch, "y") == 0) { printf("学号:"); scanf("%d", &stu[m].num); for (i = 0; i < m; i++) if (stu[i].num == stu[m].num) { printf("学号已存在!"); _getch(); fclose(fp); return; } printf("姓名:"); scanf("%s", stu[m].name); printf("性别:"); scanf("%s", stu[m].sex); printf("出生年:"); scanf("%d", &stu[m].year); printf("出生月:"); scanf("%d", &stu[m].month); printf("出生日:"); scanf("%d", &stu[m].day); printf("c语言:"); scanf("%f", &stu[m].C); printf("高数:"); scanf("%f", &stu[m].math); printf("大学物理:"); scanf("%f", &stu[m].physics); stu[m].sum = stu[m].C + stu[m].math + stu[m].physics; stu[m].avg = stu[m].sum / 3; if (fwrite(&stu[m], LEN, 1, fp) != 1) { printf("can not save!"); _getch(); } else { printf("%s saved!\n", stu[m].name); m++; } printf("continue?(y/n):"); scanf("%s", ch); } fclose(fp); printf("OK!\n"); }
时间: 2024-04-28 15:22:10 浏览: 83
void in() {
int i, m = 0;
char ch[2];
FILE* fp;
if ((fp = fopen("d:/学生系统/student.txt", "ab+")) == NULL) {
printf("can not open\n");
return;
}
while (fread(&stu[m], LEN, 1, fp) == 1) {
m++;
}
fclose(fp);
if (m == 0) {
printf("No record!\n");
}
else {
system("cls");
show();
}
if ((fp = fopen("d:/学生系统/student.txt", "ab")) == NULL) {
printf("can not open\n");
return;
}
printf("please input(y/n):");
scanf("%s", ch);
while (strcmp(ch, "Y") == 0 || strcmp(ch, "y") == 0) {
printf("学号:");
scanf("%d", &stu[m].num);
for (i = 0; i < m; i++) {
if (stu[i].num == stu[m].num) {
printf("学号已存在!");
_getch();
fclose(fp);
return;
}
}
printf("姓名:");
scanf("%s", stu[m].name);
printf("性别:");
scanf("%s", stu[m].sex);
printf("出生年:");
scanf("%d", &stu[m].year);
printf("出生月:");
scanf("%d", &stu[m].month);
printf("出生日:");
scanf("%d", &stu[m].day);
printf("c语言:");
scanf("%f", &stu[m].C);
printf("高数:");
scanf("%f", &stu[m].math);
printf("大学物理:");
scanf("%f", &stu[m].physics);
stu[m].sum = stu[m].C + stu[m].math + stu[m].physics;
stu[m].avg = stu[m].sum / 3;
if (fwrite(&stu[m], LEN, 1, fp) != 1) {
printf("can not save!");
_getch();
}
else {
printf("%s saved!\n", stu[m].name);
m++;
}
printf("continue?(y/n):");
scanf("%s", ch);
}
fclose(fp);
printf("OK!\n");
}
修改说明:
1. 删除了 while (!feof(fp)) 循环,因为这种方式会导致最后一个数据重复读入。
2. 修改了打开文件的方式,将 "wb" 修改为 "ab",这样可以在文件末尾添加数据。
3. 将读取文件和写入文件的操作分开,避免因为文件指针位置不正确而导致的错误。
4. 修改了文件指针的关闭方式,在函数的各个分支中都关闭了文件指针,避免了文件指针未关闭的风险。
阅读全文