题目 解决代码及点评 /* 4. 将存放在worker1.rec中的职工数据按工资高低排序, 将排好序的各记录存放在 worker2.rec中(用 fread和fwrite函数)。 */ #include stdio.h #include stdlib.h
题目
解决代码及点评
/*4. 将存放在worker1.rec中的职工数据按工资高低排序,
将排好序的各记录存放在 worker2.rec中(用 fread和fwrite函数)。
*/
typedef struct Staff_9_4
{
int num;
char name[30];
char sex[5];
int age;
float salary;
} Employee;
/*
读取员工信息
*/
void readAllInfo94(Employee *tempEmp,int fileType)
{
Employee temp;
FILE *fp = NULL;
if (fileType == 1)
{
fopen_s(&fp, "worker1.rec","rb");
}
else if (fileType == 2)
{
fopen_s(&fp, "worker2.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 sortAllEmp94(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 saveAllInfo94(Employee * emp,int n)
{
FILE *fp = NULL;
fopen_s(&fp, "worker2.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 = 10;
Employee emp[N];
//读取所有员工保存到emp
printf("排序前的数据:\n");
readAllInfo94(emp,1);//参数1表示打开worker1.rec文件
//给emp排序
sortAllEmp94(emp,N);
//保存排序后的员工信息
saveAllInfo94(emp,N);
printf("排序后的数据:\n");
//排序后员工的信息
readAllInfo94(emp,2);//参数2表示打开worker2.rec文件
system("pause");
}
代码编译以及运行
由于资源上传太多,资源频道经常被锁定无法上传资源,同学们可以打开VS2013自己创建工程,步骤如下:
1)新建工程
2)选择工程
3)创建完工程如下图:
4)增加文件,右键点击项目
5)在弹出菜单里做以下选择
6)添加文件
7)拷贝代码与运行
程序运行结果
代码下载
解压密码:c.itcast.cn