您好我的问题如下;
我有这个结构
struct item{
char id[5];
int ing[10];
float qtd[10];
};
我有一个包含信息的二进制文件,我想删除一个选定的ID,我尝试了这个
int remove(){
FILE *origem;
FILE *copia;
char menu[10];
struct item aux;
origem=fopen("menu.bin","rb");
copia=fopen("temp.bin","wb");
if(origem==NULL || copia==NULL)
return;
do{
printf("name to delete");
scanf("%s",&menu);
if(stricmp(menu,aux.id)!=0)
fwrite(&aux,sizeof(aux),1,copia);
}while(fread(&aux,sizeof(aux),1,origem)==1);
fclose(origem);
fclose(copia);
remove("menu.bin");
rename("temp.bin","menu.bin");
}
你可以帮帮我吗?
我想复制除我选择的ID之外的cotents。
提前谢谢。
答案 0 :(得分:0)
尝试实施以下内容,至少看看会发生什么。在这种情况下,您的程序将只接受1个ID来尝试从二进制文件中删除,而不是从二进制文件读入的每个结构中获取新的ID进行比较。
int remove(){
FILE *origem;
FILE *copia;
char menu[10];
struct item aux;
origem=fopen("menu.bin","rb");
copia=fopen("temp.bin","wb");
if(origem==NULL || copia==NULL)
return;
printf("name to delete");
scanf("%s",&menu);
// to read first record into struct aux
fread(&aux,sizeof(aux),1,origem);
do{
if(stricmp(menu,aux.id)!=0)
fwrite(&aux,sizeof(aux),1,copia);
}while(fread(&aux,sizeof(aux),1,origem)==1);
fclose(origem);
fclose(copia);
remove("menu.bin");
rename("temp.bin","menu.bin");
}
答案 1 :(得分:0)
将printf
/ scanf
内容移到循环之外,使用while(fread(...)) { ... }
代替do { ... } while(fread(...))
(有点无意义来检查ID,也许在你读完之前写一下来自文件)。