TA的每日心情 | 开心 2014-6-18 08:29 |
---|
签到天数: 14 天 [LV.3]偶尔看看II
滴水大师
 
- 积分
- 2345
|
题目
解决代码及点评
- <pre code_snippet_id="91880" snippet_file_name="blog_20131202_1_2646179" class="cpp" name="code"></pre><pre code_snippet_id="91880" snippet_file_name="blog_20131202_1_2646179" class="cpp" name="code"><pre code_snippet_id="91880" snippet_file_name="blog_20131202_1_2646179" class="cpp" name="code"><pre code_snippet_id="91880" snippet_file_name="blog_20131202_1_2646179" class="cpp" name="code">/*
- 4. 将存放在worker1.rec中的职工数据按工资高低排序,
- 将排好序的各记录存放在 worker2.rec中(用 fread和fwrite函数)。
- */
- #include <stdio.h>
- #include <stdlib.h>
- 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 = temp;
- printf("num = %d,name = %s,sex = %s,age = %d,salary = %f\n",
- tempEmp.num,tempEmp.name,tempEmp.sex,tempEmp.age,tempEmp.salary);
- fread(&temp,sizeof(temp),1,fp);
- tempEmp = 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.salary < emp[j].salary)
- {
- tempEmp = emp;
- emp = 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,sizeof(emp),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");
- }</pre><br><br></pre></pre>
|
|