Hard Light Productions Forums
Off-Topic Discussion => General Discussion => Topic started by: MicroPsycho on June 17, 2006, 01:02:20 pm
-
In a c++ file I'm writing for school I want to be able replace strings within a text file without altering the rest of the file.
Example from the text file (this an album database thing) with descriptions of what they are supposed to be in brackets:
AlbumA (name of album)
ArtistA (name of artist)
lost (stautus)
0 (location, int value)
AlbumB
ArtistB
damaged
1
my question is, how do I change, for example "ArtistA" to "Nightwish" without affecting the rest of the file. I've been using ifstream and ofstream commands. I've tried outputting a change with ofstream and it just deletes the rest of the file and writes in the change, and I know this won't accomplich what I want, but when I use ostream with ios::app it just slaps the change I want to make right on the end, messing up my database thingy, like so:
ArtistA
AlbumA
lost
0
AlbumB
ArtistB
damaged
1
Nightwish
As I said, this is for school, and is supposed to be written in c++, so please no comments telling me to use another program. Any other help is appreciated.
-
Erm, you need to re-write (as in, write a stream to file) the entire file each time anyway. Multi-dimensional arrays may offer an (elegant) solution, but I've not done enough work with them to explain how. :nervous:
-
Read the contents into a variable (or an instance of the string class, which would do nicely) until you hit a word you want to replace. Skip it and add the replacement word instead, then continue reading the rest of the file. Once you hit the end, dump the whole thing back into the file.
-
In general under most file systems you can only ever write to a file by appending data to it. This means if you want to change bits in a file, you have to read it in its entirety, alter the bits in memory, and then write the contents of memory back to a new file which overwrites the existing one. So do what Shade said, basically. :)