仅用 fprintf 和 fscanf 替换文本文件中的字符串 [英] Replace a string in text file with just fprintf and fscanf

查看:50
本文介绍了仅用 fprintf 和 fscanf 替换文本文件中的字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

抱歉问这么简单的问题,这是我作业的一部分,我被卡住了.如你所见

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; }

只接受 fscanf、fprintf.

Nothing other than fscanf, fprintf is accepted.

感谢您的帮助.

完整代码已更新,分配已更改,单个文件需要替换,我不允许使用第二个文件.

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.

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);

这篇关于仅用 fprintf 和 fscanf 替换文本文件中的字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆