Windows std::fstream modify file after open()?

Viewed 40

I'm a bit confused about this working on Windows with standard c++ lib.

Having this code:

std::fstream _fs;
_fs.open('file.txt', std::fstream::in | std::fstream::out | std::ios_base::ate);

and file.txt:

abcdefg
SUB

Being 'SUB' hex value 0x1A

After the open(), without any write() or close(), I found that file.txt is modified. I found this debugging the code and stopping it after the open().

file.txt is modified (modify date in file also) without the SUB value, I mean, the file.txt is now:

abcdefg

Is this correct? or am I doing something wrong with open() modes?

Hope anybody can point me on this.

Thanks!

1 Answers

This happens because MS-DOS used that character as an end-of-stream marker, and Windows has some special handling for it in text mode.

The Windows documentation for fopen (which using fstream eventually boils down to) says

In text mode, CTRL+Z is interpreted as an EOF character on input. In files that are opened for reading/writing by using "a+", fopen checks for a CTRL+Z at the end of the file and removes it, if it is possible. This is done because using fseek and ftell to move within a file that ends with CTRL+Z may cause fseek to behave incorrectly near the end of the file.

and Ctrl+Z is the SUB character.

Related