File IO Question...
I was wondering how, in C++, you would go about modifying a certain line of a file and replacing it with another string. For example, I want to replace line 16 on file "lines.txt" with the string:
This is line 16.
Is this possible? Or if not, is it possible to do a search for a string and to replace it? For example, replacing the string "This is line 15" with the string "This is not line 16." Thanks in advance.
Altering a file
I'm not exactly sure if you are dealing with a text or binary file, but if you construct some function that can parse out lines from a text file, you can then build a class that holds a list of each line. You can then save each line of text into your new object. If you want to change a line of text, simply access it from the objects list(there would be a number of ways to find the line you're after) and save the object. You'll need to create an ofstream object as such:
This will allow you to save all the member data of your object. Note, only member data is saved, no other members.
ofstream fout(fileName, ios::binary);
fout.write((char*)&<Object name>, sizeof<Object name>);
I have seen several members asking questions similar to yours. In general, there is not elegant solutions. The best solution is to read each line from top to bottom and change whatever line accordlingly.
- rename source file to temp
- read in one line at a time
- update and output each line to destination file
- remove temp file
Research the standard 'string' class. There are a wide variety of 'find' and 'replace' member functions,as well as a 'swap' member function.
I was educated to the fact that binary files are non-portable (right here on the Board!) so you might want to bear that in mind when dealing with your own file. Text files are preferred. (Got it from a very reliable source, though I don't know where she is. :( )
Kuphryn's advice is good, but I would cringe a little at the mechanics of reading a "narrative" line-by-line, looking for a specific 'string', and comparing. There is the overhead of reading and writing to be dealt with as well.
As Kuphryn suggests, this has been a topic of discussion before, and, shamefully, I've not tested it, so...well, you've given me something to work on.
Good luck. :)