简体   繁体   中英

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.

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"

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.

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. 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.

Further, consider checking the return value of scanf() and 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);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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