#include <stdio.h> #include <stdlib.h> #include <string.h> #define MAX_RECORDS 1000 struct Employee { int id; char name[50]; char department[50]; float score; }; struct Employee records[MAX_RECORDS]; struct Employee sorted_records[MAX_RECORDS]; int num_records = 0; void create_record() { if (num_records >= MAX_RECORDS) { printf("The number of records has reached the maximum limit!\n"); return; } struct Employee new_record; printf("Please enter the employee ID: "); scanf("%d", &new_record.id); printf("Please enter the employee name: "); scanf("%s", new_record.name); printf("Please enter the employee department: "); scanf("%s", new_record.department); printf("Please enter the employee score: "); scanf("%f", &new_record.score); records[num_records] = new_record; num_records++; } void save_records() { FILE *fp; fp = fopen("records.dat", "rb"); if (fp == NULL) { printf("Failed to open file!\n"); return; } fwrite(records, sizeof(struct Employee), num_records, fp); fclose(fp); printf("Records have been saved to file successfully!\n"); } 回答并解决文件保存打开是乱码的问题
时间: 2024-01-14 12:05:20 浏览: 71
C语言头文件 LIST.H
在函数save_records()中,文件打开模式应该为"wb" (写入二进制),而不是"rb" (读取二进制)。修改代码如下:
```c
void save_records() {
FILE *fp;
fp = fopen("records.dat", "wb");
if (fp == NULL) {
printf("Failed to open file!\n");
return;
}
fwrite(records, sizeof(struct Employee), num_records, fp);
fclose(fp);
printf("Records have been saved to file successfully!\n");
}
```
另外,还需要注意一下读取和写入的顺序需要一致。如果读取时使用了"rb"模式,那么保存时也应该使用"rb"模式。同理,如果读取时使用了"r"模式,那么保存时也应该使用"w"模式。
阅读全文