结构体数组 使用 fwrite 重新覆盖写入 编译通过,程序就执行到这一步,就错误了
程序代码:# include <stdio.h>
# include <stdlib.h>
# include <windows.h>
# include <string.h>
struct Employee
{
char name[20];
char sex[5];
char deparment[20];
double pay;
};
void SaveEmp(struct Employee[],int,int);//保存员工数据
void LoadEmp(struct Employee[],int *);//载入员工数据
void Result(struct Employee[],int *);//浏览员工信息
void Revise(struct Employee[],int *);//修改员工信息
void NewSaveEmp(struct Employee[],int);//覆盖保存数据
void NewSaveEmp(struct Employee emp[],int emp_number)
{
FILE * fp;
int i = 0;
fopen("emp.dat", "wb");
for(i = 0;i < emp_number; i++)
{
if(fwrite(&emp[i], sizeof(struct Employee), 1, fp) != 1 )
{
printf("写入失败!\n");
}
}
fclose(fp);
}
void LoadEmp(struct Employee emp[],int * emp_number)
{
FILE * fp;
int i = 0;
if((fp = fopen("emp.dat","rb"))==NULL)
{
printf("无法打开员工数据文件\n");
exit(0);
}
while (fread(&emp[i], sizeof(struct Employee), 1, fp) == 1 && i < 50)
{
i++;
}
* emp_number = i;
if (feof(fp))
{
fclose(fp);
}
}
void Result(struct Employee emp[],int * emp_number)
{
system("cls");
system("title 员工信息");
printf("\n\n\n\n\t\t读取中...");
Sleep(2000);
system("cls");
LoadEmp(emp,emp_number);
printf("\n\n\t\t员工信息:\n\n\n");
printf("\t\t姓名 性别 部门 工资");
for (int i = 0; i < * emp_number; i++)
{
printf("\n\n\t\t%-10s %-10s %-10s %-15.2f",emp[i].name,emp[i].sex,emp[i].deparment,emp[i].pay);
printf("\n\n");
}
printf("\n\n\n");
system("pause");
}
void Revise(struct Employee emp[],int * emp_number)
{
int i,find = 0;
char str[20];
char c,ch = 'y';
system("cls");
system("title 修改信息");
fflush(stdin);
LoadEmp(emp,emp_number);
printf("\n\t\t--------------------修改员工信息------------------\n");
while ((ch=='y')||(ch=='Y'))
{
printf("\n\n\t\t请输入员工的姓名:");
scanf("%s",str);
for (i = 0;i < * emp_number;i++)
{
if (strcmp(str, emp[i].name) == 0)
{
printf("\n\n\t\t您要修改的员工信息为:\n\n\n");
printf("\t\t姓名 性别 部门 工资");
printf("\n\n\t\t%-10s %-10s %-10s %-15.2f",emp[i].name,emp[i].sex,emp[i].deparment,emp[i].pay);
find = 1;
break;
}
}
fflush(stdin);
if (find = 1)
{
printf("\n\n\t\t请重新输入修改的员工信息为:\n\n\n");
printf("\n\t\t员工的姓名:");
scanf("%s",emp[i-1].name);
printf("\n\t\t员工的性别:");
scanf("%s",emp[i-1].sex);
printf("\n\t\t员工的部门:");
scanf("%s",emp[i-1].deparment);
printf("\n\t\t员工的工资:");
scanf("%lf",&emp[i-1].pay);
fflush(stdin);
printf("\n\t\t是否继续修改员工信息(y/n)?:");
scanf("%c",&ch);
fflush(stdin);
}
else
{
printf("\n\t\t输入的名字错误!\n");
}
}
NewSaveEmp(emp,* emp_number);//重新生成数据文件
system("cls");
system("pause");
}
int main(void)
{
struct Employee emp[50];
int choose,emp_number = 0;
Revise(emp,&emp_number);
Result(emp,&emp_number);
return 0;
}








