Author Topic: File IO in C++ replacing strings  (Read 869 times)

0 Members and 1 Guest are viewing this topic.

File IO in C++ replacing strings
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.
Derek Smart is his own oxymoron.

 

Offline vyper

  • 210
  • The Sexy Scotsman
Re: File IO in C++ replacing strings
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:
« Last Edit: June 17, 2006, 02:01:29 pm by vyper »
"But you live, you learn.  Unless you die.  Then you're ****ed." - aldo14

 

Offline Shade

  • 211
Re: File IO in C++ replacing strings
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.
Report FS_Open bugs with Mantis  |  Find the latest FS_Open builds Here  |  Interested in FRED? Check out the Wiki's FRED Portal | Diaspora: Website / Forums
"Oooooooooooooooooooooooooooooooooooooooh ****ing great. 2200 references to entry->index and no idea which is the one that ****ed up" - Karajorma
"We are all agreed that your theory is crazy. The question that divides us is whether it is crazy enough to have a chance of being correct." - Niels Bohr
<Cobra|> You play this mission too intelligently.

  
Re: File IO in C++ replacing strings
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. :)