Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
469 views
in Technique[技术] by (71.8m points)

c++ - Why does ofstream("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 doesn't say that ios::app cannot be combined with ios::trunc.

What are the exact semantics of ios::app and ios::trunc?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

The filebuf constructor to which these flags are passed has behaviours based on those flags 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 that table.

[C++11: 27.9.1.4/2]: [..] If mode is not some combination of flags shown in the table then the open fails.

Those are the semantics.

[C++11: 27.9.1.7/2] & [C++11: 27.9.1.11/2] show us that the mode is passed from the stream object to the buffer object.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...