我有一个程序,它的目的是创建一个员工文件,然后用户可以从创建的文件中删除、更新或检索记录,我遇到的问题是,当用户输入2以删除记录并且该记录被删除功能删除时(该功能传输除3之外的所有记录,但它一直给出这样的错误"打开文件时出错"我相信这是因为文件在执行删除功能后被删除,有人能指导我或告诉我我的代码出了什么问题吗
这是我的代码:
#include <stdio.h>
#include <string.h>
#define KEY_SIZE 100
typedef struct employee{
int id;
char name[40];
float pay;
}EMP;
void CreateEmployee();
void DisplayRecord();
void DeleteRecord(int );
void menuEmployee();
void StoreTemp(struct employee data[],FILE *fp,int ,int );
int main() {
menuEmployee();
return 0;
}
void menuEmployee(){
int choice=0;
printf(" Please select an Optionn");
puts("");
printf("t1:Create Employeen");
printf("t2:Delete Employeen");
printf("t3:Update Employeen");
printf("t4:Retrieve Employeen");
printf("t5:Display Employeen");
puts("");
printf("t 6:Exitnt ");
scanf("%d",&choice);
switch((choice-1)){
case 0:
CreateEmployee();
break;
case 1:
DeleteRecord(3);
DisplayRecord();
break;
case 2:
//UpdateEmployee();
break;
case 3:
//RetrieveEmployee();
break;
case 4:
DisplayRecord();
break;
case 5:
exit(0);
default:
printf("No such option Exist");
break;
}
}
void DeleteRecord(int id){
EMP test[KEY_SIZE];
FILE *fp;
FILE *tfp;
int length;
int i =0;
fp=fopen("employee.txt","r");
tfp=fopen("temp.txt","a");
if(fp != NULL){
length=ReadContents(test,fp,id);
length=length-1;
}
StoreTemp(test,tfp,length,id);
fclose(fp);
remove("employee.txt");
rename("temp.txt","employee.txt");
fclose(tfp);
}
int ReadContents(struct employee test[],FILE *fp,int id)
{
int count=0;
int i;
while(!feof(fp)){
fscanf(fp,"%i %s %f",&test[count].id,test[count].name,&test[count].pay);
count++;
}
return count;
}
void CreateEmployee(){
char choice ='y';
int i=0;
long int pos;
EMP x[20];
FILE *fp;
FILE *keyfp;
fp = fopen("employee.txt","a");
keyfp =fopen("Key.txt","a");
if (fp==NULL){
printf("File not created");
}
while((choice == 'Y') || (choice =='y')){
printf("Enter the employee's id:");
scanf("%i",&x[i].id);
fprintf(fp,"%it",x[i].id);
printf("nEnter the employee's name:");
scanf("%s",x[i].name);
fprintf(fp,"%st",x[i].name);
printf("nEnter the employee's pay:");
scanf("%f",&x[i].pay);
fprintf(fp,"%.2ftn",x[i].pay);
printf("nEnter another employee?n");
printf("Y - Yes N - No:n");
scanf("n%c",&choice);
i++;
}
fclose(fp);
fclose(keyfp);
menuEmployee();
}
void StoreTemp(struct employee data[],FILE *fp,int length,int id){
int i=0;
for(i=0;i<length;i++){
if(data[i].id != id){
fprintf(fp,"%it%st%.2fn",data[i].id,data[i].name,data[i].pay);
}
}
}
void DisplayRecord(){
EMP temp;
FILE *fp = fopen("employee.txt", "r");
if(fp != NULL)
{
printf("IDtNAMEtSALARYn");
while(1)
{
fscanf(fp, "%i %s %f", &temp.id, temp.name, &temp.pay);
if (feof(fp))
break;
printf("%it%st%.2fn",temp.id, temp.name, temp.pay);
}
fclose(fp);
}
else
{
printf("An error occurred opening the filen");
}
}
您正在尝试重命名一个仍然打开的文件。交换这两条线路:
rename("temp.txt","employee.txt");
fclose(tfp);
对此:
fclose(tfp);
rename("temp.txt","employee.txt");