We help IT Professionals succeed at work.

Replacement of text within file

dclaydon
dclaydon asked
on
What is the easiest way to replace text within a file?

What I need to do is  replace single and multiple lines within the resource file for the program with data obtained from the user.

I believe the easiest way would be use a CStdioFile (so you can read whole lines from the file).

I know what is going to be added where into the file and I known what it is going to replace (even if I have to read it back in). I know the location of the new text.

What I'm realy after is how to insert more characters into the same space easily and how to delete chacacters from the file to the start of the next location.

{ie I need to replace 3 lines with 3 lines but the length may be different - longer or shorter).

Regards
Dave
Comment
Watch Question

The easiest way is to
1) create a temporary output file
2) start copying data from original file to new output file.
3) stop at new insertion point an write in new data skipping that same amount of lines in the old file.
4) copy the rest of the old input file out to the new output file.
5) erase old file.  Rename new file to old name.
CERTIFIED EXPERT
Author of the Year 2009

Commented:
This alternative is rarely considered by veteran programmers who are stuck in the 64K or 640K box.  Unless the file over 100MB (25 full-length novels), this is feasible:

1) Read the entire file into memory
2) Set the file pointer back to the beginning of the file
3) Rewrite the entire file, replacing text as you go.

-- Dan

Commented:
I think you forgot this question. I will ask Community Support to close it unless you finalize it within 7 days. Unless there is objection or further activity,  I will suggest to accept "Triskelion" comment(s) as an answer.

If you think your question was not answered at all, you can post a request in Community support (please include this link) to refund your points.
The link to the Community Support area is: http://www.experts-exchange.com/commspt

PLEASE DO NOT ACCEPT THIS COMMENT AS AN ANSWER!
======
Werner

Explore More ContentExplore courses, solutions, and other research materials related to this topic.