I am facing problem while overwriting a file at a particular position in C++. I have opened my file using ios::app|ios::binary
. Then I seek to that position which I want to overwrite. But instead of overwriting it, I append from the end of the file. Any suggestions?
Asked
Active
Viewed 247 times
0

nikolas
- 8,707
- 9
- 50
- 70

user2764874
- 3
- 1
-
8What do you think `ios::app` does? – Jesse Good Sep 10 '13 at 12:45
-
2remove the ios::app option? – Theolodis Sep 10 '13 at 12:46
-
1About `ios_base::app` (`§27.5.3.1.4`): `seek to end before each write` – Marcin Łoś Sep 10 '13 at 12:46
-
if remove it then it will overwrite whole file. – user2764874 Sep 10 '13 at 12:53
-
1http://stackoverflow.com/questions/6427698/write-to-the-middle-of-an-existing-binary-file-c – doctorlove Sep 10 '13 at 12:56
2 Answers
9
You need to specify ios::in
as well as ios::out
. It overwrites if you have only ios::out
(default in ofstream
). As stated ios::app
means data is written to the end of the file, which is not what you want.

Mats Petersson
- 126,704
- 14
- 140
- 227
0
You can open your file with ios::in|ios::out|ios::binary. After that you should use seekp() to seek to the desired position of the file before the write.

Diego Giagio
- 1,027
- 7
- 7
-
1Using only `ios::out` will empty the file, you need `ios::in` to prevent the file from being emptied (or `ios::app` if you want to write only to the end. – Mats Petersson Sep 10 '13 at 13:00