Search and replace char in same text file

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • anii
    New Member
    • Oct 2007
    • 8

    Search and replace char in same text file

    Hi there,

    I've got this piece of code, but I'm having trouble getting it to write the changes into the file.

    What I'm trying to do is:
    • Read text file
    • Find user specified character (eg. what to replace all the a's)
    • Replace the character (eg. replace all a's with b's)
    • Write to the same text file


    Code:
    #include <stdio.h>
    #include <string.h>
    
    #define MAX_LEN_SINGLE_LINE     1000
    
    int main(int argc, char *argv[])
    {
            if (argc < 4)
            {
                    fprintf(stderr, "Format should be: %s  char to replace  char replacing\n", argv[0]);
                    return 1;
            }
    
        char buffer[MAX_LEN_SINGLE_LINE+2];
        char *buff_ptr, *find_ptr, temp;
        FILE *fp1;
        size_t find_len = strlen(argv[2]);
    
        fp1 = fopen(argv[1],"r");
    
        while(fgets(buffer,MAX_LEN_SINGLE_LINE+2,fp1))
        {
            buff_ptr = buffer;
            while ((find_ptr = strstr(buff_ptr,argv[2])))
            {
                while(buff_ptr < find_ptr)
                    fputc((int)*buff_ptr++,fp1);
    
                fputs(argv[3],fp1);
                buff_ptr += find_len;
            }
            fputs(buff_ptr,fp1);
        }
         
        fclose(fp1);
    
        return 0;
    }
    At the moment it compiles fine (with a few warnings) but when I check the file it does not have the changes made to it.

    User would input something like: ./a.out myfile.txt a b
    (that is - take myfile.txt - replace all a's and replace with b's)

    Any help would be greatly appreciated!
  • donbock
    Recognized Expert Top Contributor
    • Mar 2008
    • 2427

    #2
    On line 19 you open the file for reading ("r"). Try opening it for update ("r+"). Refer to the fopen man page for details.

    Comment

    • anii
      New Member
      • Oct 2007
      • 8

      #3
      Hi donbock, thanks for your reply. I've changed the ("r") to ("r+") and tweeked the rest of the code to rewind and little and write.

      Comment

      Working...