0

The code is supposed to overwrite or clear the file when Yes is entered, but it still does so when No or anything else is entered.

void createCanteenFoodFile()
{

    FILE* fp;
    int i,t=0;
    char ans;
    struct food foodie={0,"","",0,0.0,0.0,0.0,0.0};

    if ((fp = fopen("food", "wb"))==NULL)
    {
        printf("Cannot open file \n");
    }
    else
    {
        printf("Are you sure you want to create a new file?\nThis will overwrite any previous data\n\n");
        printf("Type Yes or No\n");
        scanf("%c",&ans);
        if(ans=='Y' or ans=='y')
        {
            for (i=0;i<=100;i++)
            {
                fwrite(&foodie,sizeof(struct food),1,fp);//food file created
            }
            printf("\n------------------------------------------------------------\n");
            printf("\t\t        FILE CREATED\t\t\n");
            printf("------------------------------------------------------------\n");
            fflush(stdin);
        }
        else if(ans=='N' or ans=='n')
        {
            printf("Option denied\n");
            fflush(stdin);
        }
        else
        {
            printf("\t\t   ERROR - Invalid option\n");
            fflush(stdin);
        }
        fclose(fp);
    }
}
Jonathan Leffler
  • 698,132
  • 130
  • 858
  • 1,229
Kusuo
  • 13
  • 2

1 Answers1

1

Opening a file with the "wb" flags will remove all previous content of the file, regardless of if you ever write to it. To solve your issue you would have to move your call to fopen till after you got confirmation that the file should be deleted.

depsterr
  • 71
  • 6