为什么ofstream在这里工作,而不是fstream?

我试图了解std::ofstream和之间的区别std::fstream。我有这个代码:

#include <iostream>
#include <fstream>
#include <string>
using namespace std;

int main () {
    string line;
    //create an output stream to write to the file
    //append the new lines to the end of the file
    ofstream myfileI ("input.txt", ios::app);
    
    
    if (myfileI.is_open())
    {

        myfileI << "nI am adding a line.n";
        cout << myfileI.fail() << "n";
        myfileI << "I am adding another line.n";
        cout << myfileI.fail() << "n";

        myfileI.close();
    }
    else cout << "Unable to open file for writing";

失败位返回 0,因此它正在写入。

但是当我使用完全相同的代码但使用fstream而不是使用时,失败位返回 1ofstream

input.txt 就是这样:

Read and write to this file. 

What am I doing here?

This is not a good example of a file

回答

我看不实用您描述的两种情况之间区别。

唯一的技术区别是ofstream始终ios::out启用标志,该标志将添加到您指定的任何标志中。而fstream拥有ios::inios::out标志启用默认,但将由您指定任何标志被覆盖。

因此,在ofstream您以ios::out | ios::app模式打开文件的情况下,而fstream在仅ios::app模式下打开文件的情况下。

但是,两个流都委托给std::filebuf,并且根据此参考for std::filebuf::open()out|appapp模式的行为方式完全相同 - 就像fopen(filename, "a")被使用一样,因此如果文件存在,它们都将“附加到文件”,如果文件存在则“创建新”不存在。


以上是为什么ofstream在这里工作,而不是fstream?的全部内容。
THE END
分享
二维码
< <上一篇
下一篇>>