程序通过定义学生结构体变量,存储了学生的学号、姓名和3门课的成绩。所有学生数据均以二进制方式输出到文件中。函数 fun 的功能是重写形参 filename 所指文件中最后一个学生的数据,即用新的学生数据覆盖该学生原来的数据,其他学生的数据不变。按照这个要求修改代码,程序的主体结构不变“”“(char *filename,STU n){ FILE *fp; fp=fopen(filename,"rb"); fseek(fp,1L*sizeof(STU),2); fwrite(n, sizeof(STU), 1, fp); fclose(fp); } void main(){ STU t[N]= {{10001,"MaChao", 91, 92, 77},{10002,"CaoKai",75, 60, 88}, {10003,"LiSi", 85, 70, 78},{10004,"FangFang",90, 82, 87}, {10005,"ZhangSan",95, 80, 88} }; STU n={10006,"ZhaoSi", 55, 70, 68},ss[N]; int i,j; FILE *fp; fp=fopen("student.dat","wb"); fwrite(t, sizeof(STU),N,fp); fclose(fp); fp=fopen("student.dat","rb"); fread(ss, sizeof(STU),N,fp); fclose(fp); printf("\n\nThe original data:\n\n"); for (j=0;j<N;j++) { printf("No: %ld Name:%-8sScores:",ss[j].sno, ss[j].name); for (i=0;i<3;i++) printf("%6.2f", ss[j].score[i]); printf("\n"); } fun("student.dat",n); printf("\n\nThe data after mdifing :\n\n"); fp=fopen("student.dat","rb"); fread(ss, sizeof(STU), N,fp); fclose(fp); for (j=0; j<N; j++) { printf("nNo: %ld Name: %-8s,Scores:",ss[j].sno, ss[j].name); for (i=0; i<3; i++) printf("%6.2f",ss[j].score[i]); printf("\n"); } } ename, "rb")”
时间: 2024-04-25 15:27:00 浏览: 163
修改后的代码如下:
```c
#include <stdio.h>
#define N 5
typedef struct student {
long sno;
char name[10];
float score[3];
} STU;
void fun(char *filename, STU n) {
FILE *fp;
fp = fopen(filename, "rb+");
if (fp == NULL) {
printf("Cannot open file!\n");
return;
}
fseek(fp, -sizeof(STU), SEEK_END);
fwrite(&n, sizeof(STU), 1, fp);
fclose(fp);
}
int main() {
STU t[N] = {
{10001, "MaChao", {91, 92, 77}},
{10002, "CaoKai", {75, 60, 88}},
{10003, "LiSi", {85, 70, 78}},
{10004, "FangFang", {90, 82, 87}},
{10005, "ZhangSan", {95, 80, 88}}
};
STU n = {10006, "ZhaoSi", {55, 70, 68}}, ss[N];
int i, j;
FILE *fp;
fp = fopen("student.dat", "wb");
if (fp == NULL) {
printf("Cannot open file!\n");
return 0;
}
fwrite(t, sizeof(STU), N, fp);
fclose(fp);
fp = fopen("student.dat", "rb");
if (fp == NULL) {
printf("Cannot open file!\n");
return 0;
}
fread(ss, sizeof(STU), N, fp);
fclose(fp);
printf("\n\nThe original data:\n\n");
for (j = 0; j < N; j++) {
printf("No: %ld Name:%-8sScores:", ss[j].sno, ss[j].name);
for (i = 0; i < 3; i++)
printf("%6.2f", ss[j].score[i]);
printf("\n");
}
fun("student.dat", n);
printf("\n\nThe data after modifying:\n\n");
fp = fopen("student.dat", "rb");
if (fp == NULL) {
printf("Cannot open file!\n");
return 0;
}
fread(ss, sizeof(STU), N, fp);
fclose(fp);
for (j = 0; j < N; j++) {
printf("No: %ld Name:%-8sScores:", ss[j].sno, ss[j].name);
for (i = 0; i < 3; i++)
printf("%6.2f", ss[j].score[i]);
printf("\n");
}
return 0;
}
```
修改的主要内容:
1. 函数 `fun` 中的文件打开模式由 "rb" 修改为 "rb+",以便进行读写操作。
2. 在函数 `fun` 中,使用 `fseek` 定位到文件结尾前一个学生的位置,再使用 `fwrite` 函数将新的学生数据写入该位置。
3. 在主函数中,输出原始数据时,将 "n" 改为 "No",并修改输出格式。
4. 在主函数中,修改后的数据输出时,将 "n" 改为 "No",并修改输出格式。
阅读全文