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
  • 730,956
  • 141
  • 904
  • 1,278
Kusuo
  • 13
  • 2
  • 4
    If `fopen("food", "wb")` works, the content of the file is already gone. You should ask before you open the file. – mch Mar 10 '20 at 16:21
  • 2
    `if(ans=='Y' or ans=='y')`??? `or` is not a proper C operator. – Andrew Henle Mar 10 '20 at 16:21
  • 1
    [The written versions of the logical operators](//stackoverflow.com/q/2376448) – 001 Mar 10 '20 at 16:29
  • `fwrite` does not create a file; `fopen` does. The misplaced comments demonstrate the misunderstandintg. Move `// food file created` from the `fwrite` to the `fopen`. – William Pursell Mar 10 '20 at 17:24
  • @Yunnosch (also @Andrew Henle): please read C11 [§7.9 Alternative spellings ``](http://port70.net/~nsz/c/c11/n1570.html#7.9). Granted, it isn't often used, but it certainly can be used. – Jonathan Leffler Mar 11 '20 at 01:39
  • Note the caveats about [Using `fflush(stdin)`](https://stackoverflow.com/questions/2979209/using-fflushstdin). – Jonathan Leffler Mar 11 '20 at 01:41
  • @JonathanLeffler Thanks for notifying me of that interesting header. – Yunnosch Mar 11 '20 at 06:29

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