题目
解决代码及点评
/*
7. 删除worker2.rec中某个序号的职工记录,
再存入原文件中(用fread和fwrite函数)
*/
#include
#include
typedef struct Staff_9_7
{
int num;
char name[30];
char sex[5];
int age;
float salary;
} Employee;
/*
读取员工信息
*/
void readStaInfo_7(Employee *tempEmp)
{
Employee temp;
FILE *fp = NULL;
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 saveEmpInfo97(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 = 11;
int num;
int index = 0;
Employee emp[N];
Employee newEmp[N - 1];
readStaInfo_7(emp);
printf("请输入要删除员工的编号:\n");
scanf_s("%d",&num);
for (int i = 0; i < N; i++)
{
if (num == emp[i].num)
{
continue;
}
else
{
newEmp[index++] = emp[i];
}
}
saveEmpInfo97(newEmp,N - 1);
readStaInfo_7(newEmp);
system("pause");
}
代码编译以及运行
由于资源上传太多,资源频道经常被锁定无法上传资源,同学们可以打开VS2013自己创建工程,步骤如下:
1)新建工程
2)选择工程
3)创建完工程如下图:
4)增加文件,右键点击项目
5)在弹出菜单里做以下选择
6)添加文件
7)拷贝代码与运行
程序运行结果
代码下载
http://download.csdn.net/detail/yincheng01/6694119解压密码:c.itcast.cn