I just made a program to delete a record from a binary file, but the problem is even if the program finds a match with the name, it does't actually delete it from the file when I write the records on a temporary file. Do I get wrong in the else condition perhaps?
#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;
}
fbarefers to file named bynewname, and file handletemprefers to file named byoldname, but those variable names do not suggest any correspondence. You could try using better names (eg.fba/fba_nameandtemp/temp_name).remove(temp_name);it would be easier to spot error.