Is the default mode of ofstream implementation defined?

后端 未结 2 1136
星月不相逢
星月不相逢 2021-01-16 08:16

Given the following code:

std::ofstream stream(\"somefile\");

if (!stream)
{
   return 1;
}

When invoking .write(....) and using

相关标签:
2条回答
  • 2021-01-16 09:08

    When I run your code on windows using g++ and libstdc++, i get the following result:

    expect: 32
    file size: 33
    

    So the problem is not compiler specific, but rather OS specific.

    While C++ uses a single character \n to represent a line ending in a string, Windows uses two bytes 0x0D and 0x0A for a line ending in a file. This means that if you write a string into a file in text mode, all occurrences of the single character \n are written using those two bytes. That's why you get additional bytes in the file size of your examples.

    0 讨论(0)
  • 2021-01-16 09:20

    The default mode used by the stream constructor is ios_base::out. As there is no explicit text mode flag, this implies the stream is opened in text mode. Text mode only has an effect on Windows systems, where it converts \n characters to CR/LF pairs. On POSIX systems it has no effect, and text and binary modes are synonymous on these systems.

    0 讨论(0)
提交回复
热议问题