Sorry for such easy question, this is part of my assignment and I'm stuck. As you can see
#include <stdio.h>
int main (void){
FILE *menu;
FILE *update;
FILE *updatewrite;
menu = fopen("menu.txt","w");
char selection,name[10],updateid,dump ;
int mealnum,i,j,id,price ;
start:
scanf("%c%c",&selection,&dump);
if (selection =='r'){
printf ("Enter the number of meals to be entered\n");
scanf("%d",&mealnum);
for(i=0;i<mealnum;i++){
printf("Enter the name of me1al\n");
scanf("%s",&name);
printf("Enter the ID of meal\n");
scanf("%d",&id);
printf("Enter the Price of meal\n");
scanf("%d",&price);
fprintf(menu,"%s %d %d\n",name,id,price);
}
fclose(menu);
}
else if(selection =='u'){
update = fopen("menu.txt","r");
int count=0;
while(fscanf(update,"%s %d %d\n",name,&mealnum,&price) != EOF){
printf("Update %s %d %d?\n Y to update any other key for next",name,mealnum,price);
scanf("%c",updateid);
count++;
break;
}
printf("Enter the new name of meal\n");
scanf("%s",name);
printf("Enter the new ID of meal\n");
scanf("%d",&id);
printf("Enter the new Price of meal\n");
scanf("%d",&price);
fclose(update);
updatewrite = fopen("/home/mbp/menu.txt","w+");
for(j=0;j<count;j++){fscanf(updatewrite,"%s %d %d\n",name,mealnum,price);} //trying to move buffer to proper overwriting location by looping one less times
fprintf(updatewrite,"%s %d %d\n",name,mealnum,price);
fclose(updatewrite);}
else if(selection =='d'){}
else if(selection =='s'){}
else if(selection =='b'){}
else if(selection =='q'){
return 0;
}
else{printf ("Not VALID!");}
goto start;
return 0; }
Nothing other than fscanf, fprintf is accepted.
Thanks for any help.
EDIT: full code updated, assigment changed, single file needs to replaced, I'm not allowed use a second file.
Since you already have two files, open both files at the same time. As you read each line from one, you either write the same data to the other, or new data to the other, depending on the user's choice.
You would need to do more than scan and print. here is some pseudo code for you:
Here is a simple example program
May be this can work. I fixed two mistake about you code .
The problem of "it does not works" would benefit with more detail as in how odes it not work. Here is my best shot.
Change "%c" to " %c"
The OP code mixes
scanf("%s",...
withscanf("%c",...
. This is a problem if before thescanf("%c",...
, somewhere in unposted code, you performed ascanf("%s",...
or the like.The
scanf("%s",buf)
consumes all leading white space and then puts the following non-white text inbuf
, leaving the "enter" (\n
) in the input buffer. A followingscanf("%c",...
will then read the (\n
) and not even wait fro you to type something likey
. By changing "%c" to " %c", that (\n
) and additional white space will get consumed (and tossed) and then youry
will get scanned.Further, consider checking the return value of scanf() and fscanf(). It will certianly help you debug your code.