gemexas
gemexas

Reputation: 203

Writing to specific position in a file

I have

fstream output;
output.open(fname, ios::out | ios::trunc); //file
for (int i=0; i<flength; i++)
    output.put('1');

I want to overwrite different length of data to different locations in the file. Data is characters.

Lets say there is 111111111111111111111111111111111, I want to write

11   111111333111!!!!!!1    11441111

Upvotes: 2

Views: 22318

Answers (5)

Vishal S
Vishal S

Reputation: 73

The Best way is to rewrite the whole file into another file after making required changes.

std::ifstream fin("yourfile.txt");
remove("yourfile.txt");

Copy the stream before removing your file. This can help you preserve the name of the file.

Upvotes: 0

etarion
etarion

Reputation: 17169

You can't "insert" things in the middle of the file - the only inplace operations you can do is writing the exact same amount of bytes that you are trying to overwrite, i.e. writing without changing the length of the file. If you need to write a string of different length (as in your example) you have to rewrite the whole file from the point where you ended your write operation (store original in a buffer and rewrite).

Upvotes: 2

vitaut
vitaut

Reputation: 55705

You can use seekp to set the position of the put pointer and write at the specific position in the file, e.g.

 output.seekp(10);
 output.put('!');

Upvotes: 3

Moo-Juice
Moo-Juice

Reputation: 38820

Check out ostream::seekp, here. Position the file-pointer to the desired location before writing.

Upvotes: 0

unwind
unwind

Reputation: 400109

Use seekp() to set the writing position in the file stream.

Upvotes: 2

Related Questions