// 001.cpp : 定义控制台应用程序的入口点。
//
/************************************************************************/
/* 将存放的worker.rec职工数据按照工资高低进行排序写到文件中 */
/************************************************************************/
#include "stdafx.h"
#define N 10
typedef struct workData{
int num;
char name[30];
char sex[5];
int age;
float salary;
}Employee;
//read data
void readWordData(Employee* employee, int fileType)
{
if ( !employee ) return;
FILE *fp;
Employee temp = {0};
if ( 1 == fileType )
{
fopen_s(&fp, "workdata.rec", "rb");
}
else if( 2 == fileType )
{
fopen_s(&fp, "workdata2.rec", "rb");
}
if ( fp )
{
fread(&temp, sizeof(temp), 1, fp);
while ( !feof(fp) )
{
*employee++ = temp;
fread(&temp, sizeof(temp), 1, fp);
}
}
fclose(fp);
}
void writeWordData(Employee* employee, int size)
{
if ( !employee ) return;
FILE *fp;
fopen_s(&fp, "workdata2.rec", "wb");
if ( fp )
{
fwrite(employee, size, 1, fp);
fflush(fp);
fclose(fp);
}
}
//sort
void sortEmployeeBySalary(Employee* employee, int length)
{
//45.25 20.25 23.21 1.56 56.98
//56.98 45.25 20.25 23.21 1.56
#if 1
Employee temp = {0};
for(int i = 0;i < length;++i)
{
for(int j = i+1; j < length;++j)
{
if ( employee[j].salary > employee[i].salary )
{
temp = employee[i];
employee[i] = employee[j];
employee[j] = temp;
}
}
}
#endif
#if 0
Employee temp = {0};
bool bChange = false;
for(int i = length -1;i >= 0;--i)
{
for(int j = 0;j < i;++j)
{
if ( employee[j].salary < employee[j+1].salary )
{
temp = employee[j];
employee[j] = employee[j+1];
employee[j+1] = temp;
bChange = true;
}
}
if ( !bChange )
{
break;
}
}
#endif
}
void display(Employee* employee, int length, int printfType)
{
if ( !employee ) return;
if ( 1 == printfType )
{
printf("未按高工资排序:\n");
}
else if( 2 == printfType )
{
printf("按高工资排序后:\n");
}
for(int i = 0;i < length; ++i)
{
printf("%d %s %s %d %f\n", employee[i].num, employee[i].name, employee[i].sex, employee[i].age, employee[i].salary);
}
printf("\r\n");
}
int _tmain(int argc, _TCHAR* argv[])
{
Employee employee[N] = {0};
readWordData(employee, 1);
display(employee, N, 1);
sortEmployeeBySalary(employee, sizeof(employee)/sizeof(Employee));
writeWordData(employee, sizeof(employee)/sizeof(Employee));
readWordData(employee, 2);
display(employee, N, 2);
return 0;
}
#if 0
void initData()
{
Employee employee[] =
{
{ 1,"a1", "男", 23, 5678.67},
{ 2,"a2", "男", 24, 1678.67},
{ 3,"a6", "男", 23, 3678.67},
{ 4,"a1", "女", 26, 8678.67},
{ 5,"b1", "男", 23, 9678.67},
{ 6,"c1", "男", 29, 2678.67},
{ 7,"d1", "女", 35, 12678.67},
{ 8,"d1", "男", 23, 2678.67}
};
FILE* fp;
fopen_s(&fp, "workdata.rec", "wb");
if ( fp )
{
fwrite(employee,sizeof(employee), 1, fp);
printf("success!");
fclose(fp);
}
}
#endif