使用全局顺序表结构解决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"); } 这段代码保存后打开查看是乱码的问题
时间: 2024-01-17 18:04:03 浏览: 60
ff.rar_C++ FILE* ff_ff文件系统_文件操作_精简文件系统
如果要使用全局顺序表结构来解决这个问题,可以将结构体数组 `records` 定义为全局变量,并在保存和读取数据时使用该全局变量。具体代码如下:
```c++
#include <stdio.h>
#include <stdlib.h>
#define MAX_RECORDS 100
struct Employee {
int id;
char name[20];
int age;
};
struct Employee records[MAX_RECORDS];
int num_records = 0;
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");
}
void load_records() {
FILE *fp;
fp = fopen("records.dat", "rb");
if (fp == NULL) {
printf("Failed to open file!\n");
return;
}
num_records = fread(records, sizeof(struct Employee), MAX_RECORDS, fp);
fclose(fp);
printf("Records have been loaded from file successfully!\n");
}
int main() {
// 其他代码
return 0;
}
```
在这个代码中,我们将结构体数组 `records` 和记录数 `num_records` 定义为全局变量,可以在 `save_records` 和 `load_records` 函数中直接使用这些全局变量来保存和读取数据。
阅读全文