tags:

views:

255

answers:

2

I want to make modifications to the middle of a text file using c++, without altering the rest of the file. How can I do that?

A: 

Generally, open the file for reading in text mode, read line after line until the place you want to change, while reading the lines, write them in a second text file you opened for writing. At the place for change, write to the second file the new data. Then continue the read/write of the file to its end.

ysap
I want to avoid doing it this way.
Phenom
+3  A: 

If the replacement string is the same length, you can make the change in place. If the replacement string is shorter, you may be able to pad it with zero-width spaces or similar to make it the same number of bytes, and make the change in place. If the replacement string is longer, there just isn't enough room unless you first move all remaining data.

Ben Voigt
That sounds good, but what's the code for that? Let's assume that the string is the same length.
Phenom
Well, it depends on which I/O library you're using, the C standard library, C++ standard library, or an OS-specific API. But generally there are three steps. When opening the file, specify write access without truncation, e.g. fopen(fname, "r+"). Seek to the desired location with e.g. fseek. Write the new string with e.g. fwrite or fprintf. In some APIs, like Windows OVERLAPPED or linux aio, you can say "write to this location" without a separate seek step.
Ben Voigt
fseek doesn't work with ofstream. How can it be done with ofstream?
Phenom
`ostream::seekp` http://www.cplusplus.com/reference/iostream/ostream/seekp/
jschmier
I tried seekp and when I wrote to the file it overwrote everything.
Phenom
Ok, I'll emphasize part of my previous comment "when opening the file, specify write access WITHOUT TRUNCATION". From http://stdcxx.apache.org/doc/stdlibug/30-3.html, <quote>For output file streams the open mode out is equivalent to out|trunc, that is, you can omit the trunc flag</quote>. So use a bidirectional fstream instead of an ofstream.
Ben Voigt
So what's the code for that?
Phenom
USE fstream INSTEAD OF ofstream! How much clearer can I be?
Ben Voigt
Finally got it to work. That was tough.
Phenom
Glad you finally got there. In the future you'll get an answer quicker and with a lot less frustration if you tell us: What libraries, what compiler and whether you want it portable, what you've tried so far, the behavior you're seeing now, and what you wanted. For this question, it would have helped to say "I'm trying to overwrite just part of a file using ofstream. Here's the code (you actually did put that in another question). The new data shows up in the file, but no matter what I do the previous contents disappear. How can I make edits while keeping the other parts of the file."
Ben Voigt