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?

8 Years
Discussion Span
Last Post by deceptikon

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.


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.




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.



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.


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.



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");

        buff_ptr = buffer;
        while ((find_ptr = strstr(buff_ptr,text2find)))
            while(buff_ptr < find_ptr)


            buff_ptr += find_len;


    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.



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!


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.


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.

This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.