ios::app 在 C++ 中不也意味着 ios::out 吗?

Does ios::app not also imply ios::out in C++?

我看到另一个类似的question,其中的答案是:

Using app implies out. The standard specifies that app and out|app have the same result, equivalent to C fopen in mode "a".

但我的情况似乎没有发生。我做了一个小代码来测试这个。

#include<iostream>
#include<fstream>
#include<stdlib.h>
using namespace std;

int main()
{
    fstream f;
    char ch[10]={"Hello"};
    f.open("Hello.txt",ios::app);
    f<<ch;
    if(f.fail())
    {
        cout<<"Failed to write\n";
    }
    cout<<ch<<endl;
    f.close();
    system("pause");
}

这给了我输出:

Failed to write
Hello

此外,它没有向文件写入任何内容 Hello.txt 这是否意味着 ios::app 并不意味着 ios::out?或者,我是不是弄错了?

此外,我尝试添加 ios::out

#include<iostream>
#include<fstream>
#include<stdlib.h>
using namespace std;

int main()
{
    fstream f;
    char ch[10]={"Hello"};
    f.open("Hello.txt",ios::app|ios::out);
    f<<ch;
    if(f.fail())
    {
        cout<<"Failed to write\n";
    }
    cout<<ch<<endl;
    f.close();
    system("pause");
}

在这次尝试中,程序确实工作了,它也写入了文件。

虽然这对我来说非常有说服力 ios::app 没有实现 ios::out 但对 question 的回应仍然让我怀疑,因为如果我们想要追加那么我们当然想要写入文件。

std::ios_base::outstd::ios_base::appstd::filebuf::open()一起使用的行为(好吧,实际上,std::basic_filebuf<...>::open()在Table 132中指定。相关的三行对于此讨论,前三个将 std::ios_base::openmode 映射到与 fopen() 一起使用的文件打开模式(这又定义了语义)。这些行定义了以下映射:

  1. std::ios_base::out -> "w"
  2. std::ios_base::app -> "a"
  3. std::ios_base::out | std::ios_base::app -> "a"

即除std::ios_base::app外是否指定std::ios_base::out并不重要。如果行为因 std::ios_base::out 存在而不同,则实施应该是错误的。

在 Win7 + Explorer 上使用第一个旧的 c++ syle 代码进行测试显示了 writen 输出。 但是同样的执行在 notepad++ 下运行,NppExec 和 follow 脚本显示另一个结果:

npp_save
set GWDIR=G:\MinGW471
cd "$(CURRENT_DIRECTORY)"
$(GWDIR)\bin\g++ "$(FILE_NAME)" -o $(NAME_PART) -std=c++11 -march=native -O3
NPP_RUN $(NAME_PART)

如果我没记错的话,在旧的 Windows Explorer 下,第一个代码显示了我们喜欢的内容。

此 c++ 变体显示了我们在 Explorer 和 NppExec 下预期的结果:

#include<iostream>
#include<fstream>
#include<stdlib.h>
using namespace std;

int main()
{
    char ch[10]={"Hello"};
    ofstream f("Hello.txt",ios::app);
    f<<ch;
    if(f.fail())
    {
        cout<<"Failed to write\n";
    }
    cout<<ch<<endl;
    system("pause");
}

请原谅我的英语。