/* 6. 在文件 worker2.rec 中插入一个新职工的数据,并使插入后仍保持原来的顺序 (按工资高低顺序插入到原有文件中),然后写入worker3.rec中。 */ #include <stdio.h> #include <stdlib.h> typedef struct Staff_9_6 { int num; char name[30]; char sex[5]; int age; float salary; } Employee; /* 读取员工信息 */ void readStaInfo96(Employee *tempEmp,int fileType) { Employee temp; FILE *fp = NULL; if (fileType == 2) { fopen_s(&fp, "worker2.rec","rb"); } else if (fileType == 3) { fopen_s(&fp, "worker3.rec","rb"); } if (fp) { int i = 0; fread(&temp,sizeof(temp),1,fp); while(!feof(fp)) { tempEmp[i] = temp; printf("num = %d,name = %s,sex = %s,age = %d,salary = %f\n", tempEmp[i].num,tempEmp[i].name,tempEmp[i].sex,tempEmp[i].age,tempEmp[i].salary); fread(&temp,sizeof(temp),1,fp); tempEmp[i] = temp; i++; } fclose(fp); } else { printf("open file failed!"); } } /* 按照工资从高到低排序 */ void sortEmp96(Employee *emp,int n) { Employee tempEmp; for (int i = 0; i < n - 1; i++) { for (int j = i + 1; j < n; j++) { if (emp[i].salary < emp[j].salary) { tempEmp = emp[i]; emp[i] = emp[j]; emp[j] = tempEmp; } } } } /* 保存员工信息 */ void saveEmpInfo96(Employee * emp,int n,int fileType) { FILE *fp = NULL; if (fileType == 2) { fopen_s(&fp, "worker2.rec","wb"); } else if (fileType == 3) { fopen_s(&fp, "worker3.rec","wb"); } if (fp) { for (int i = 0; i < n; i++) { fwrite(&emp[i],sizeof(emp[i]),1,fp); } fclose(fp); } else { printf("open file failed!"); } } void main() { const int N = 11; Employee emp[N]; //readStaInfo(emp,2); Employee newEmp; printf("请输入第新员工的姓名:\n"); scanf_s("%s",&(newEmp.name)); printf("请输入第新员工的性别:\n"); scanf_s("%s",&(newEmp.sex)); printf("请输入第新员工的编号:\n"); scanf_s("%d",&(newEmp.num)); printf("请输入第新员工的年龄:\n"); scanf_s("%d",&(newEmp.age)); printf("请输入第新员工的工资:\n"); scanf_s("%f",&(newEmp.salary)); emp[N - 1] = newEmp; //sortEmp(emp,N); saveEmpInfo96(emp,N,2); saveEmpInfo96(emp,N,3); readStaInfo96(emp,3); system("pause"); }
由于资源上传太多,资源频道经常被锁定无法上传资源,同学们可以打开VS2013自己创建工程,步骤如下:
1)新建工程
2)选择工程
3)创建完工程如下图:
4)增加文件,右键点击项目
5)在弹出菜单里做以下选择
6)添加文件
7)拷贝代码与运行
解压密码:c.itcast.cn