Thread: How to find and replace a string in a file

  1. #1
    Registered User
    Join Date
    Jan 2002
    Posts
    4

    Unhappy How to find and replace a string in a file

    Hi All,
    It has been along time since I did C. I need to search for a stringA withen a text file and if found to replace it with stringB.
    Sample:
    StringA="Hello"
    StringB="Help"
    Sample File content(it can be any combanations):
    line1="XYZ"
    line2="XYZ KLM ABCHelloXYZ ABC"

    I need to find and replace "Hello" in line2

    I hope some have done this before or close to it.

    Thanks,

  2. #2
    The Artful Lurker Deckard's Avatar
    Join Date
    Jan 2002
    Posts
    633
    The library function strstr(), if you are permitted to use it, is just what you need to find one string within another.
    Jason Deckard

  3. #3
    Registered User
    Join Date
    Sep 2001
    Posts
    752
    You'll nead to read the file into an array (fread), modify the array, then rewrite the file using the array (fwrite).

    Basically, your array is gonna be one huge string. And, the function you'll use is ...
    char * strstr(cs, ct);
    // return pointer to first occourance ofstring ct in cs, or NULL if not present.
    Callou collei we'll code the way
    Of prime numbers and pings!

  4. #4
    ATH0 quzah's Avatar
    Join Date
    Oct 2001
    Posts
    14,826
    You can actually get this done without using a buffer if you feel like it. Or rather, without a large buffer. All you need is one as long as the word you're looking to replace.
    Code:
    read from file until file is done
       strcmp( word, bufer )
       if ! match
           write buffer to new file
       else
          write replacement to new file
    close input file
    remove input file
    rename output file to input file
    You can actually even do this with a single integer as your 'buffer' with only a slight modification.

    Quzah.
    Hope is the first step on the road to disappointment.

  5. #5
    Registered User
    Join Date
    Jan 2002
    Posts
    4

    Question

    I really thank you for your replies. But I think I am way below your experties.
    1-I attempted to use vVv code, but i encountered some compilation errors (i am using Miracle C), I made few changes to get it to work, but, it kept writing string2 to the end of file.
    2-I tried the strstr and the fread, I still don't know how to replace the string.
    the description of strstr sounds like just "search/find", I am missing the "replace" see my code:
    #include <stdio.h>
    #include <system.h>
    void main()
    {
    FILE *fp;
    char *dest, *h;
    int n;
    if((fp = fopen("test.txt","r")) == NULL) return;
    dest = malloc(1000000);
    h=strstr(dest, "%include%");
    printf("read %s",h);
    return;
    }

    Again, thanks for the help.

  6. #6
    and the hat of int overfl Salem's Avatar
    Join Date
    Aug 2001
    Location
    The edge of the known universe
    Posts
    39,660
    Talk about making a mountain out of a molehill

    Code:
    #include <stdio.h>
    #include <string.h>
    
    int main ( ) {
        char buff[BUFSIZ];      // the input line
        char newbuff[BUFSIZ];   // the results of any editing
        char findme[] = "hello";
        char replacewith[] = "world";
        FILE *in, *out;
    
        in = fopen( "file.txt", "r" );
        out= fopen( "new.txt", "w" );
    
        while ( fgets( buff, BUFSIZ, in ) != NULL ) {
            if ( strstr( buff, findme ) != NULL ) {
                // do 1 or more replacements
                // the result should be placed in newbuff
                // just watch you dont overflow newbuff...
            } else {
                // nothing to do - the input line is the output line
                strcpy( newbuff, buff );
            }
            fputs( newbuff, out );
        }
    
        fclose( in );
        fclose( out );
        return 0;
    }

  7. #7
    Registered User
    Join Date
    Jan 2002
    Posts
    4

    Question

    Hi all,
    thanks again for the replies. my findings are:
    1-the code by Salem:
    a)I had compile error on[BUFSIZE].
    F:\C\compile\searc2.c: line 7: Parse Error, expecting `']'' or `NUMBER'
    'char buff[BUFSIZE]'
    b)I replaced with a number[800]. it compiled but the results were not correct.

    2-The code by vVv:
    a) fseek( fd, -( i ), SEEK_CUR ); the -(i) was not accepted. After I removed it, the code worked but it kept writting to end of file:
    String2="MS Serif"
    string="Arial"
    file content:
    "[Fonts]

    [FontSubstitutes]
    Helv=MS Sans Serif
    Tms Rmn=MS Serif
    Times=Times New Roman"
    Output:
    "[Fonts]

    [FontSubstitutes]
    Helv=MS Sans Serif
    Tms Rmn=MS Serif
    Times=Times New RomanArial"

    as you see "Arial" was apended to end of my ini file instead of replacing "MS Serif"

  8. #8
    The Artful Lurker Deckard's Avatar
    Join Date
    Jan 2002
    Posts
    633
    So, um... how's your code coming along, salzouby? ;)
    Jason Deckard

  9. #9
    and the hat of int overfl Salem's Avatar
    Join Date
    Aug 2001
    Location
    The edge of the known universe
    Posts
    39,660
    > a)I had compile error on[BUFSIZE].
    Then you need to get a compiler which is more ANSI-C compatible.

    > b)I replaced with a number[800]. it compiled but the results were not correct.
    Of course it doesn't - its a guide, not an answer...

    The
    &nbsp; while ( fgets( ) ) fputs()
    will copy a text file

    Anything else you do between the fgets and fputs is your problem, not mine.

  10. #10
    Registered User
    Join Date
    Nov 2001
    Posts
    1
    i think this is the solution u needed. hope it works

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

    void main()
    {
    FILE *fp;
    int i=0,len_string;
    char SearchText[]="Hello"; /* You can replace this text */
    char ReplaceText[]="Help"; /*You can also replace this text. */
    char temp[30];
    fp=fopen("filename","a+");
    rewind(fp); /* for going to start of file. */
    if(fp==NULL)
    {
    printf("File couldn't be opened ");
    exit(0);
    }
    len_string=strlen(SearchText);
    while(1)
    {
    for(i=0;i<len_string;i++) temp[i]=fgetc(fp);
    temp[i+1]=NULL;
    if(stricmp(SearchText,temp)==0) /* the stricmp() is used for comparing both string. */
    {
    fprintf(fp,"%s ",ReplaceText);
    fclose(fp);
    exit(1);
    }
    fseek(fp,-(len_string-1)L,1);
    }
    fclose(fp);
    }

    Hope this code provides you the answer , but this code replaces the first occurence of the searching text and not the second occurence.
    Last edited by ms_skanda; 01-15-2002 at 04:12 AM.

  11. #11
    Registered User
    Join Date
    Jan 2002
    Posts
    4

    Thumbs up

    I really like to thank all of you how provided code and ideas to my issue.
    When I posted my issue I was hoping for a quick and easy way to do simple routine (find and replace) thinking that there must be a function that do such thing. I choose C because of the size of the .exe file.
    I am a VB programmer and have not done C since the college days(that will tell you how bad my C is). Finally I decided to use VB it is a larger EXE. but it takes less than 15 minutes to code and 5 lines of code to encounter all possible scenarios.

    Again thanks to all.

  12. #12
    Registered User
    Join Date
    Sep 2010
    Posts
    1
    I just happen to the same question ,and don't konw how to resolve it.

  13. #13
    Registered User
    Join Date
    Sep 2006
    Posts
    8,868
    Welcome to the forum, Lpvoid!

    There are many ways to replace a string, or part of a string in a file. So what are the specifics in your case?

    Usually, a good way is to follow logic like this:

    1) Open the file
    2) While it has data, read the contents into a buffer
    3) If the buffer has the data you want to replace, then replace it, right inside the buffer.
    4) write the buffer contents out to the new file
    5) when the file being read, is empty, delete it
    6) and name the new file, with the old file name

    There are other ways, but this is as clear a way to do it, as any, and has the smallest chance of messing up the original file contents, imo.

    Post up a 4 or 5 line example file for the original, and also, an example of the output file you want to have. Talking specifics is always better than talking about generalities with C.

    Whenever you post code, click on the # icon in the advanced editing window, and paste your program between the code tags it will give you. That makes your code 100% better to study.

  14. #14
    and the hat of int overfl Salem's Avatar
    Join Date
    Aug 2001
    Location
    The edge of the known universe
    Posts
    39,660
    Another is to read the forum rules and then you would know that bumping a thread which is 8 YEARS old with nothing more than a "me too" comment is a really bad thing.

    Closed.
    If you dance barefoot on the broken glass of undefined behaviour, you've got to expect the occasional cut.
    If at first you don't succeed, try writing your phone number on the exam paper.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Find and replace within a string?
    By clancyPC in forum C Programming
    Replies: 3
    Last Post: 03-20-2009, 07:28 AM
  2. Inventory records
    By jsbeckton in forum C Programming
    Replies: 23
    Last Post: 06-28-2007, 04:14 AM
  3. Find & Replace Newest File
    By peckitt99 in forum C++ Programming
    Replies: 5
    Last Post: 06-09-2007, 05:37 AM
  4. Errors with program to replace string with another
    By Dan17 in forum C Programming
    Replies: 3
    Last Post: 09-14-2006, 10:15 AM
  5. what does this mean to you?
    By pkananen in forum C++ Programming
    Replies: 8
    Last Post: 02-04-2002, 03:58 PM