0

I wrote a code to replace a word in a file with another that I take in input. In input I ask what word the user wants to replace and with what word he wants to replace it. The code works, but he replace every occurrence of the word. I tryed in different ways but I don't know how to let it works. Can someone help me? Thank you

char nomefile2[50];
int linea;
write(conn_fd,"\nPREGO INSERIRE IL NOME DELL'APPELLO:",strlen("PREGO INSERIRE IL NOME DELL'APPELLO:\n"));               
      recv(conn_fd,nomefile2,50,0);         
puts(nomefile2);
write(conn_fd,"\nPREGO INSERIRE LA PAROLA DA SOSTITUIRE:",strlen("PREGO INSERIRE LA PAROLA DA SOSTITUIRE:\n"));
recv(conn_fd,trova,30,0);   
write(conn_fd,"\nPREGO INSERIRE LA NUOVA PAROLA:",strlen("PREGO INSERIRE LA NUOVA PAROLA:\n"));
recv(conn_fd,sostituisci,30,0); 
write(conn_fd,"\nPREGO INSERIRE LA LINEA IN CASO DI OMONIMI/VOTI:",strlen("PREGO INSERIRE LA LINEA IN CASO DI OMONIMI/VOTI:\n"));       
           FullRead(conn_fd,(char *)&linea, sizeof(linea));
FILE *Input,*Output;

Input = fopen(nomefile2, "r");
Output = fopen(filetemp, "w");


if(NULL == Input)
{
    printf("\nCould not open file");
   break;
}

printf("\ntrova:%s\n", trova);
printf("\nsostituisci:%s\n", sostituisci);

// For each line...
while(NULL != fgets(Buffer, 4095, Input))
{
    char *Stop = NULL;
    char *Start = Buffer;

    while(1)
    {

        /*getting the first location of the source string*/
        Stop = strstr(Start, trova);
        if(NULL == Stop)
        {
            fwrite(Start, 1, strlen(Start), Output);
            break;
        }
        printf("\nTrovata a linea  <%d>",line);


        fwrite(Start, 1, Stop - Start, Output);
        /*writting Replacement string to the output file**/
        fwrite(sostituisci, 1, strlen(sostituisci), Output);

        /*moving the pointer to the next char of source string*/
        Start = Stop + strlen(trova);    }
    line++;
}




fclose(Input);
fclose(Output);
remove(nomefile2);
rename(filetemp, nomefile2);
Corax
  • 5
  • 3
  • @alk that would not copy the rest of it. Corax, use a flag... start it with zero, set it to 1 after the first replacement, only do the replacement if the flag is zero. – msb Mar 11 '15 at 17:54
  • @Corax do you mean you need just replace the first occurrence instead of all occurrences? Please make it clear. – Ram Mar 11 '15 at 17:56
  • @Ram not the first occurrence but a specifc occurrence. My file is a list of person who has an id, name and surname. If the user wants to change a name, but there are more name like that I want to recognize it by ID. But how can I recognize by ID? – Corax Mar 12 '15 at 09:47
  • @Corax Please add these details to the question by editing it. I am helping you improve your question so that it gets upvoted and gets answers faster. – Ram Mar 12 '15 at 13:27

0 Answers0