很抱歉问了这么简单的问题,这是我作业的一部分,我被困住了。正如你所看到的
#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; }
除了 fscanf、fprintf 之外,不接受任何其他内容。
感谢您的帮助。
编辑:完整代码已更新,分配已更改,需要替换单个文件,我不允许使用第二个文件。
最佳答案
由于您已经有两个文件,因此请同时打开这两个文件。当您读取其中的每一行时,您可以将相同的数据写入另一行,或者将新数据写入另一行,具体取决于用户的选择。
FILE *update = fopen("menu2.txt", "r");
FILE *menu = fopen("/home/mbp/menu.txt","w+");
for (...) {
fscanf(update, ...);
if (user_wants_update()) {
get_new_info(...);
fprintf(menu, ...); /* print the new info */
} else {
fprintf(menu, ...); /* print the old info */
}
}
fclose(menu);
fclose(update);
关于c - 仅使用 fprintf 和 fscanf 替换文本文件中的字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18028324/