ofstream: overwriting files gives inconsistent results.

Not sure if this is the right forum for what could be a windows bug.

Running the following code compiled with VC14 and running on windows 10 gives different results depending on whether the executable is on the C: drive or an external USB drive:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
#include <fstream>

using namespace std;

int main()
{
  {
    ofstream out ("test.txt", ios::out | ios::binary);
    out << "1234567890" << endl;
  }
  
  
  {
    ofstream out ("test.txt", ios::out | ios::binary);
    out << "abcdef" << endl; 
  }  
  return 0;
}


Output when run on the C: drive:

abcdef

Output when run on the D: USB drive:

abcdef
890


It appears than when writing to an external drive, it doesn't truncate the file if the new content is shorter than the original.

Any idea what could be going on?

Rob.
Last edited on
It can be caused by the buffering of the USB drive. In the device manager you can check if it is optimised to fast writing or for safe removal.
Another cause of the problem is that << does not work properly if the stream is in binary mode.
http://stackoverflow.com/questions/14767857/unexpected-results-with-stdofstream-binary-write
Write caching is disabled on the drive.

I modified the example but it still gives the same results. The new code is:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
#include <fstream>
using namespace std;

int main()
{
  {
    ofstream out ("test.txt", ios::out | ios::binary);
    out.write ("1234567890\n", 11);
  }
  
  
  {
    ofstream out ("test.txt", ios::out | ios::binary);
    out.write ("abcdef\n", 7);
  }
  
  return 0;
}
Last edited on
Watch out for this kind of errors as they can spend a lot of your time discovering them. If you need some help you can try using some programs like checkmarx or others but it's recommended to do it on your own.
Good luck!
Ben.
More info:

The correct result is produced on windows 7.

Compiling for x64 also produces the correct result on windows 10.

The problem only occurs on Windows 10 in 32 bit mode.
Topic archived. No new replies allowed.