Why forstream ("log.txt", ios :: app | ios :: trunc); always fail?

The following code was compiled with VC ++ Nov 2012 CTP on Windows 7 x64.

#include <fstream>

using namespace std;

int main()
{
    ofstream fout("log.txt", ios::app|ios::trunc);
    if (!fout)
    {
        cout << "An error occurred!" << endl; // Always go here! Why?
    }
}

The cppreference.com website does not say that ios::appyou cannot combine with ios::trunc.

What is exact semantics ios::appand ios::trunc?

+5
source share
2 answers

The constructor filebufto which these flags are passed & dagger; has behavior based on those flags that are defined in table 132 in C ++ 11:

+-----------------------------------+-------------------+
|     ios_base flag combination     |  stdio equivalent |
| binary  in    out    trunc    app |                   |
+-----------------------------------+-------------------+
|               +                   |  "w"              |
|               +               +   |  "a"              |
|                               +   |  "a"              |
|               +       +           |  "w"              |
|        +                          |  "r"              |
|        +      +                   |  "r+"             |
|        +      +       +           |  "w+"             |
|        +      +               +   |  "a+"             |
|        +                      +   |  "a+"             |
+-----------------------------------+-------------------+
|   +           +                   |  "wb"             |
|   +           +               +   |  "ab"             |
|   +                           +   |  "ab"             |
|   +           +       +           |  "wb"             |
|   +    +                          |  "rb"             |
|   +    +      +                   |  "r+b"            |
|   +    +      +       +           |  "w+b"            |
|   +    +      +               +   |  "a+b"            |
|   +    +                      +   |  "a+b"            |
+-----------------------------------+-------------------+

As you can see, your flag combination is not found in this table.

[C++11: 27.9.1.4/2]:[..] If modeit is not any combination of flags shown in the table, then open does not work.

.

& dagger;[C++11: 27.9.1.7/2] [C++11: 27.9.1.11/2] , .

+17
  • (= append): .
  • trunc (= truncate) , .

, .

+6

All Articles