1,105,581 Community Members

find and replace string in a text file

Member Avatar
somename
Newbie Poster
17 posts since May 2008
Reputation Points: 0 [?]
Q&As Helped to Solve: 0 [?]
Skill Endorsements: 0 [?]
 
0
 

Hello. I am trying to find out how to write a function to replace a string in a text file. So far i got this:
find -> is a word i am looking for replace, rep -> new word, f1 -> my file. And i'm stuck with that piece of code:

while ( fgets( buff, BUFSIZ, f1 ) != NULL ) {
if ( strstr( buff, find ) != NULL ) {...

so i'm thinking about something like that:

strcpy(buff2, (buff - strlen(find) + strlen(rep) + 1);
fputs(buff2, f2)

where f2 is output file. So plz, maybe anyone can help me with this code?

Member Avatar
Clockowl
Posting Whiz
376 posts since May 2008
Reputation Points: 56 [?]
Q&As Helped to Solve: 28 [?]
Skill Endorsements: 0 [?]
 
-1
 

I don't get why you use fgets. If it's an ASCII file, and it should be for the thing you're trying to do, all you need to do is strstr(buff, find) and then memcpy. Not strcpy, in an ASCII file aren't any NULL bytes. Well, not that I know of. I've never encountered NULL bytes in an ASCII file.

So it'd be more like this:

//read in the whole file
char *ptr = strstr(buf, find);
memcpy(ptr, find, sizeof(char) * strlen(find));

Something like that.

Member Avatar
jephthah
Posting Maven
2,572 posts since Feb 2008
Reputation Points: 1,888 [?]
Q&As Helped to Solve: 196 [?]
Skill Endorsements: 5 [?]
 
0
 

WHOA, whoa, whoa... Clockowl.

That is so, SO wrong, I dont know where to start.

Did you even try this? have you ever tried this?

of course not, it would never even remotely work. It doesnt even make SENSE.

IMHO, you need to read more and help less. a lot less.


.

Member Avatar
jephthah
Posting Maven
2,572 posts since Feb 2008
Reputation Points: 1,888 [?]
Q&As Helped to Solve: 196 [?]
Skill Endorsements: 5 [?]
 
0
 

SOMENAME:

C does not lend itself to easily extracting and replacing arbitrary text from a file. you can do it, only if the field from which you are extracting/replacing is a FIXED WIDTH. there can not be any variation in the width of the text field.

if thats the case, then you can use a combination of functions like FSEEK, FTELL and REWIND.

if its not the case (and it tends to not be the case for typical applications), then you will need to:

--open the original file for reading
--open a new file for writing
--read orig file one line at a time, modifing as needed
--write that line to the new file.
--when done, delete the original file
--rename the new file with the original file's name.

sucks, i know. if you really need to get into serious text file manipulation, you might look into Perl. but that's a whole 'nother can of worms.


.

Member Avatar
Clockowl
Posting Whiz
376 posts since May 2008
Reputation Points: 56 [?]
Q&As Helped to Solve: 28 [?]
Skill Endorsements: 0 [?]
 
0
 

What's wrong about it? Okay, it's fixed length only, but that's like... obvious. I've parsed text in C. Never something like changing a string though, but I don't see why this method wouldn't work given it's a fixed length string/word.

Member Avatar
tesuji
Master Poster
721 posts since Apr 2008
Reputation Points: 135 [?]
Q&As Helped to Solve: 98 [?]
Skill Endorsements: 0 [?]
 
0
 

To search for strings in ascii files there exists the amazing Knuth–Morris–Pratt string searching algorithm. It is faster than anything. Try it, and you will be delighted.

Member Avatar
jephthah
Posting Maven
2,572 posts since Feb 2008
Reputation Points: 1,888 [?]
Q&As Helped to Solve: 196 [?]
Skill Endorsements: 5 [?]
 
0
 

SOMENAME:

you're essentially on the right track, and you've basically got it. i think you're getting bogged down in some detail or other.

check this out, and see how it's pretty much what you're doing:

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

#define MAX_LEN_SINGLE_LINE     120   // ?

int main()
{
    const char fileOrig[32] = "myOriginalFile.txt";
    const char fileRepl[32] = "myReplacedFile.txt";
    const char text2find[80] = "lookforme";
    const char text2repl[80] = "REPLACE_WITH_THIS";

    char buffer[MAX_LEN_SINGLE_LINE+2];
    char *buff_ptr, *find_ptr;
    FILE *fp1, *fp2;
    size_t find_len = strlen(text2find);

    fp1 = fopen(fileOrig,"r");
    fp2 = fopen(fileRepl,"w");

    while(fgets(buffer,MAX_LEN_SINGLE_LINE+2,fp1))
    {
        buff_ptr = buffer;
        while ((find_ptr = strstr(buff_ptr,text2find)))
        {
            while(buff_ptr < find_ptr)
                fputc((int)*buff_ptr++,fp2);

            fputs(text2repl,fp2);

            buff_ptr += find_len;
        }
        fputs(buff_ptr,fp2);
    }

    fclose(fp2);
    fclose(fp1);

    return 0;
}

it has a couple caveats... it requires that you #define the max length of a file line. any that exceed that length are at risk of missing an instance of the search text. could be a candidate for a carefully implemented malloc() call

also, it won't find a search text that is split across two lines. which would be a serious flaw in many situations.


.

Member Avatar
somename
Newbie Poster
17 posts since May 2008
Reputation Points: 0 [?]
Q&As Helped to Solve: 0 [?]
Skill Endorsements: 0 [?]
 
0
 

guys, thank you very much for your replies, especially jephthah, your code works great and i get it now where i got lost with my code! Thanks once again!

Member Avatar
iamadamcooke
Newbie Poster
1 post since Nov 2012
Reputation Points: 0 [?]
Q&As Helped to Solve: 0 [?]
Skill Endorsements: 0 [?]
 
0
 

jephthah or anyone else : would jephthah's code work with outputting to the SAME file? I wasnt to read in a file, replace some substrings, and output to the same file.

Member Avatar
deceptikon
Eternally Awesome
4,688 posts since Jan 2012
Reputation Points: 1,341 [?]
Q&As Helped to Solve: 688 [?]
Skill Endorsements: 104 [?]
Administrator
Featured
 
0
 

would jephthah's code work with outputting to the SAME file?

Not as-is. To be completely safe you'd want to write to a temporary file first. Then delete the original and rename the temporary to the original. Reading from and writing to the same file line by line, if it works at all due to file locking, would be very likely to corrupt subsequent reads.

You
This article has been dead for over three months: Start a new discussion instead
Post:
Start New Discussion
Tags Related to this Article