0

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;


}
4
  • 1
    Your handle fba refers to file named by newname, and file handle temp refers to file named by oldname, but those variable names do not suggest any correspondence. You could try using better names (eg. fba/fba_name and temp/temp_name). Commented Jul 3, 2018 at 8:44
  • @el.pescado I corrected, I deleted the wrong file so of course nothing changed. After changing that, everything works, thank you Commented Jul 3, 2018 at 8:46
  • I mean, if variables relate to same thing, their names should show that relation. That way, if you had remove(temp_name); it would be easier to spot error. Commented Jul 3, 2018 at 8:51
  • @el.pescado I guess you're right, I'll modify it thank you Commented Jul 3, 2018 at 8:52

1 Answer 1

3

You are removing the updated file (temp.bin, aka oldname) :

remove(oldname);

before you attempt to replace the original file (alimenti.bin, aka newname) with it :

rename(oldname,newname);

Did you mean :

remove(newname);
Sign up to request clarification or add additional context in comments.

1 Comment

Oh my, thank you! Now it works perfectly! Sorry for this stupid mistake

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.