简体   繁体   English

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

[英]Replace a string in text file with just fprintf and 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; }

Nothing other than fscanf, fprintf is accepted. 除了fscanf外,不接受fprintf。

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. 当您从一行中读取每一行时,您可以将相同的数据写入另一行,或者将新数据写入另一行,具体取决于用户的选择。

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

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" 将“%c”更改为“%c”

The OP code mixes scanf("%s",... with scanf("%c",... . This is a problem if before the scanf("%c",... , somewhere in unposted code, you performed a scanf("%s",... or the like. OP代码将scanf("%s",...scanf("%c",...混合在一起。如果在scanf("%c",...之前的未发布代码中,执行了scanf("%s",...等。

The scanf("%s",buf) consumes all leading white space and then puts the following non-white text in buf , leaving the "enter" ( \\n ) in the input buffer. scanf("%s",buf)会消耗所有前导空白,然后将以下非白色文本放入buf “ enter”( \\n保留在输入缓冲区中。 A following scanf("%c",... will then read the ( \\n ) and not even wait fro you to type something like y . By changing "%c" to " %c", that ( \\n ) and additional white space will get consumed (and tossed) and then your y will get scanned. 随后的scanf("%c",...将读取( \\n ),甚至不等您键入y 。通过将“%c”更改为“%c”,该( \\n )和其他空白将被消耗(并扔掉), 然后您的y将被扫描。

Further, consider checking the return value of scanf() and fscanf(). 此外,考虑检查scanf()和fscanf()的返回值。 It will certianly help you debug your code. 它将有效地帮助您调试代码。

You would need to do more than scan and print. 您需要做的不仅仅是扫描和打印。 here is some pseudo code for you: 这是一些伪代码供您使用:

read in line from file 1
check if line needs modification
if so
    modify line
write line to file 2

Here is a simple example program 这是一个简单的示例程序

#include <stdio.h>
#include <string.h>

int main()
{
    FILE *f1 = fopen("1.txt", "r");
    FILE *f2 = fopen("2.txt", "w");
    char line[50];

    while (fscanf(f1, "%s", line) != EOF)
    {
        if (strcmp(line, "replaceme") == 0)
        {
            strcpy(line, "replaced");
        }
        fprintf(f2, "%s", line);
    }
    fflush(f2);
    fclose(f1);
    fclose(f2);
}

May be this can work. 也许这可以工作。 I fixed two mistake about you code . 我修复了关于您的代码的两个错误。

update = fopen("menu2.txt","r");// you open a FILE and give the fileid to updata

for(j=0;j<kk;j++) {
    fscanf(update,"%s %d %d\n",name,&mealnum,&price);
    //so you have a file ,already writed format things. 
    printf("Update %s %d %d?\n Y to update any other key for next",name,mealnum,price);
    scanf("%c\n",&updateid); 
    //I think it's better use "%c\n", then you can know it not stay in buffer.  
    if(updateid == 'Y') //as we print, 'Y' to update .. 
        break;//          if you can not use goto , don't use.//goto out;   
}
//out:
// I believe you already declare all those values.
printf("Enter the name of meal\n");
scanf("%s",&name);
printf("Enter the ID of meal\n");   
scanf("%d",&id);
printf("Enter the Price of meal\n");
scanf("%d",&price);

fclose(update);// close the (FILE * ) update. In fact, I think here is you mistake.

menu = fopen("/home/mbp/menu.txt","w+");//menu is used just now.    

for(d=0;d<j-1;d++) {
   // fscanf(menu,"%s %d %d\n",name,mealnum,price);
   //here ,you overwrite you values. All you input is missing; Here is another mistake.
    int mealnum1,price1;
    char name1[10];//I don't know the size...  :)
      fscanf(menu, %s %d %d\n",&name1,&mealnum1,&price1);
}

fprintf(menu,"%s %d %d\n",name,mealnum,price);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM