C程序设计 (第四版) 谭浩强 习题10.10
习题10.10 从第9题的“职工工资文件”中删除一个职工的数据,再存回原文件。
IDE工具:VS2010
Note: 使用不同的IDE工具可能有部分差异。
代码块
方法:使用指针,函数的模块化设计,动态分配内存
说明:文件wage.dat已经存在与项目目录下。
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define N 3
typedef struct{
int num;
char name[20];
char gender;
int age;
char addr[20];
float wage;
char health;
char edu[10];
}Employee;
void initialVar(Employee **emp, int n, char **name){
*emp = (Employee*)malloc(n * sizeof(Employee));
*name = (char*)malloc(80 * sizeof(char));
}
void inputFileName(FILE **file, char *name){
printf("Enter File Name: ");
scanf("%s", name);
*file = fopen(name, "rb");
if(*file == NULL){
perror("Cannot open this file");
system("pause");
exit(0);
}
}
void readFile(FILE **file, Employee *emp, int n){
printf("Read File Info:\n");
for(int i = 0; i < n; i++){
fread(&emp[i].name, sizeof(Employee), 1, *file);
fread(&emp[i].wage, sizeof(Employee), 1, *file);
printf("Name: %-10s Wage: %-.2f\n", emp[i].name, emp[i].wage);
}
printf("\n");
fclose(*file);
}
void deleteRec(FILE **file, char *name, Employee *emp, int n, int num){
for(int i = 0; i < n; i++){
if(i == num - 1){
for(int j = i; j < n - 1; j++){
emp[j] = emp[j+1];
}
break;
}
}
*file = fopen(name, "wb");
if(*file == NULL){
perror("Cannot open this file");
system("pause");
exit(0);
}
for(int i = 0; i < n - 1; i++){
if(fwrite(&emp[i].name, sizeof(Employee), 1, *file) != 1){
perror("File Write Error");
system("pause");
exit(0);
}
if(fwrite(&emp[i].wage, sizeof(Employee), 1, *file) != 1){
perror("File Write Error");
system("pause");
exit(0);
}
}
fclose(*file);
}
void outputFileNew(FILE **file, char *name, Employee *emp, int n){
*file = fopen(name, "rb");
if(*file == NULL){
perror("Cannot open this file");
system("pause");
exit(0);
}
printf("New Employee Info:\n");
for(int i = 0; i < n; i++){
fread(&emp[i].name, sizeof(Employee), 1, *file);
fread(&emp[i].wage, sizeof(Employee), 1, *file);
printf("Name: %-10s Wage: %-.2f\n", emp[i].name, emp[i].wage);
}
printf("\n");
fclose(*file);
}
int main(){
FILE *file = NULL;
Employee *emp = NULL;
char *name = NULL;
initialVar(&emp, N, &name);
inputFileName(&file, name);
readFile(&file, emp, N);
deleteRec(&file, name, emp, N, 1);
outputFileNew(&file, name, emp, N-1);
system("pause");
return 0;
}