Is there an "overwrite" method or function in C++? For example, I have some data in a text file that I want to overwrite with other data. The data is lined up nicely kind of in columns, so I can use "setw()" to get the new data to line up, but I need it to replace the old data. I don't really want to create a new file, because 99.9999% of the data in the file will remain the same.
Just open the file for reading + writing. Seek back to the beginning of the file (or whatever you want to write new data), and start writing. Whatever you write will overwrite the data that currently exists in the file.
Not sure on exact line count, but all lines are numbered (so 15600 is the line number, but not necessarily line 15600 from the top). Maybe about ten changes are made. It's a data file I'm modifying.
Yes, that is correct. However keep in mind that files don't care about line numbers. They care about bytes. So the data you are writing has to be the exact same size as the data you want to be overwritten, or else there will be other issues.
Example text file:
1 2 3
Line 1
Line 2
Line 3
If you go the start of the file and write "foo", you'll end up with this:
1 2 3
fooe 1
Line 2
Line 3
Or if you go to the start and write "foobarbaz" you might end up with this (assuming newlines are \r\n):
Would I be okay if I were to go to line marked 15600, and, knowing that the end of the data was 100 places into the line, do a setw(100)? Assume the data there is 200.0, and I replaced it with 0.000. So I would go from:
setw outputs a bunch of spaces (100 minus whatever you output). So if you want to preserve the first 100 characters on the line, that is not the way to do it (they will get overwritten with spaces).
Instead, just seek ahead 100 characters once you found the line, and output your data without any setw.
Alright, well that poses another problem, partially something I already was worried about. I can find line 15600 by parsing a file and looking for "15600". But from there, how do I go out 100 characters (text and spaces), minus the five or so characters I want to write, to the point I want to write data? Please note that reading and writing files is something I do all the time, but I'm not very good at it - so any help will be greatly appreciated. Thank you.