滴水逆向联盟
标题:
基于visual Studio2013解决C语言竞赛题之0906文件插入
[打印本页]
作者:
大灰狼
时间:
2014-9-5 08:08
标题:
基于visual Studio2013解决C语言竞赛题之0906文件插入
题目
download.png
(24.47 KB, 下载次数: 523)
下载附件
保存到相册
2014-9-5 08:08 上传
解决代码及点评
<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">/*
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
= 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 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
.salary < emp[j].salary)
{
tempEmp = emp
;
emp
= 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
,sizeof(emp
),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");
}</pre><br><br></pre></pre>
欢迎光临 滴水逆向联盟 (http://www.dtdebug.com/)
Powered by Discuz! X3.2