ios::app 不也暗示 ios::out 在C++

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

本文关键字:ios C++ out app 暗示      更新时间:2023-10-16

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

使用app意味着out。该标准规定了应用程序和输出|应用程序 具有相同的结果,相当于模式"a"中的C fopen。

但就我而言,这似乎没有发生。我做了一个小代码来测试这一点。

#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 writen";
    }
    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 writen";
    }
    cout<<ch<<endl;
    f.close();
    system("pause");
}

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

虽然这对我来说很有说服力,ios::app没有实现ios::out但对这个问题的回答仍然让我怀疑,因为如果我们想要附加,那么我们当然想写入文件也是有道理的。

std::ios_base::outstd::ios_base::appstd::filebuf::open()一起使用的行为(实际上,std::basic_filebuf<...>::open()在表 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而异,则实现应该是错误的。

使用第一个旧的 c++ syle 代码在 Win7 + 资源管理器上的测试显示写入输出。但是同样的执行在记事本++下运行,带有folow脚本的NppExec显示了另一个结果:

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

如果我没记错的话,在旧的Windows资源管理器下,第一段代码显示了我们喜欢的内容。

这个 c++ 变体显示了我们在资源管理器和 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 writen";
    }
    cout<<ch<<endl;
    system("pause");
}

请原谅我的英语。