用C语言编写:有一磁盘文件employee,内存放职工的数据。每个职工的数据包括职工姓名、职工号、性别、年龄、住址、工资、健康状况、文化程度。今要求将职工名、工资的信息单独抽出来,另建一个简明的职工工资文件。
时间: 2023-07-04 16:04:54 浏览: 106
以下是一个简单的C语言程序,可以实现将employee文件中的职工名和工资信息抽出来并保存到salary文件中。
```c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define MAX_EMPLOYEE 1000
#define MAX_NAME 20
struct Employee {
char name[MAX_NAME];
int id;
char gender;
int age;
char address[50];
float salary;
char health[20];
char education[20];
};
int main() {
struct Employee employees[MAX_EMPLOYEE];
FILE *fp_in, *fp_out;
int num_employee = 0;
// 打开employee文件
fp_in = fopen("employee", "rb");
if (fp_in == NULL) {
printf("无法打开文件!\n");
return 1;
}
// 读取employee文件中的内容
while (fread(&employees[num_employee], sizeof(struct Employee), 1, fp_in) == 1) {
num_employee++;
}
// 关闭employee文件
fclose(fp_in);
// 打开salary文件
fp_out = fopen("salary", "w");
if (fp_out == NULL) {
printf("无法打开文件!\n");
return 1;
}
// 将职工名和工资信息写入salary文件
for (int i = 0; i < num_employee; i++) {
fprintf(fp_out, "%s %.2f\n", employees[i].name, employees[i].salary);
}
// 关闭salary文件
fclose(fp_out);
return 0;
}
```
该程序首先定义了一个结构体Employee来存储职工的数据,然后定义了一个数组employees来保存所有职工的信息。
程序通过打开employee文件,并使用fread函数读取其中的内容,将所有职工的信息存储到employees数组中。然后,程序打开salary文件,并使用fprintf函数将职工名和工资信息写入该文件中。
最后,程序关闭了employee和salary文件,并返回0表示运行成功。