c - 仅使用 fprintf 和 fscanf 替换文本文件中的字符串

标签 c scanf printf

很抱歉问了这么简单的问题,这是我作业的一部分,我被困住了。正如你所看到的

#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/

相关文章:

c - C语言中使用POSIX使二进制信号量在多个进程(不是线程,仅限进程)之间共享

c++ - 如何在 Eclipse C++ 中重构/重命名宏

c - 如何限制用户只能输入整数并拒绝 scanf 中的任何其他字符?

Code::Blocks 不显示任何输出

gcc预处理后能输出C代码吗?

c - 为什么此代码将空间 (' ' ) 分配给字符数组的特定元素?

C - 我可以使用 scanf 暂停等待用户按 Enter 的循环吗?

c - 使用 sscanf 读取带有空格和特殊字符的字符串

可以使用多个 _Generic 来创建字符串文字吗?

c++ - (Closed) C++ & Direct3D 9 - 如何绘制格式化文本? (如 printf 等)