Sign in to follow this  
GildeD

C++ File I/O Replace **PLEASE HELP**

Recommended Posts

I'm trying to change certain lines in a text file and I can't seem to find any resource which will tell me how to do this in c++. I've read all about how to read and write but how do you delete a line in a text file and replace it? - GildeD [Edited by - GildeD on May 24, 2005 5:31:33 PM]

Share this post


Link to post
Share on other sites
Perhaps this will phrase it better. I know how to write things to a file. I know how to read a file. But I can find Nothing on removing a line and replacing it. In fact i find nothing on removing at all.

Can someone please help?

- GildeD

Share this post


Link to post
Share on other sites
You need to read the whole file, then make the change/replace/whatever, and finally write it back with the same name.

Share this post


Link to post
Share on other sites
You can open a file read-write but I'm not sure if you can shorten a file this way. Rather, what you want to do is either:

1. Read the file into memory, close it, make the changes, and then write over the original file.

2. Rename the file, then open that file for reading and the original filename for writing, and copy line-by-line doing your replace until they're done. Then you erase the renamed file.

The replace operation is basically, read a line from the file or from memory, compare it to the line you want. If it isn't it, copy it, otherwise copy your replacement string, and continue.

Share this post


Link to post
Share on other sites
usually you would read in the file and write out a new one.

you could do it a line at a time.

create new file
open original file
read in a line
write out the line to the new file
change the old filename to something else
change the new filename to the old filename
once everything is done okay delete the old file

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this