我刚刚制作了一个程序来从二进制文件中删除记录,但是问题是,即使程序找到了与名称匹配的文件,当我在临时文件上写入记录时,它实际上并没有从文件中删除它。文件。在其他情况下我是否会出错?
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
typedef struct {
int dd;
int mm;
int yyyy;
}date;
struct _food
{
char category[20];
char name[30];
int amount;
data expiry;
int calories;
} food;
int main()
{
FILE* fba;
FILE* temp;
int found = 0;
char nome_t[30];
char newname[] = "alimenti.bin";
char oldname[] = "temp.bin";
fba = fopen("alimenti.bin", "rb");
temp = fopen("temp.bin", "wb");
printf("Type the name of the food you want to delete:\n");
gets(nome_t);
while(fread(&food,sizeof(food),1,fba))
{
if(strcmp(nome_t,food.name) != 0)
{
fwrite(&food,sizeof(food),1,temp);
}
else{
found = 1;
printf("Match found. Food deleted.\n");
}
}
if (!found){
printf("No match.\n");
}
fclose(fba);
fclose(temp);
remove(oldname);
rename(oldname,newname);
system("PAUSE");
return 0;
}
答案 0 :(得分:3)
您要删除更新的文件( temp.bin ,又名oldname
):
remove(oldname);
在尝试用其替换原始文件( alimenti.bin ,又名newname
)之前:
rename(oldname,newname);
您的意思是:
remove(newname);