The main thing you have to understand is: in general case, you have to rewrite the whole file. Why?
You will understand it if you look at the structure of the text file and understand what is "line". This is a string subdivided by
end-of-line strings. If one of the strings to be replaced is shorted or longer than before the change, all the text after the change should be shifted in memory.
It the file is not very big, you can read it all in memory, and then change the lines you need to change, and write it back. If the file is too big to reliably fit in memory, read each line and write it in a new (temporary) file, changing required lines. When it's done, you can rename/move the temp file to the original file.
—SA