【问题标题】:Why does ofstream work here, but not fstream?为什么 ofstream 在这里工作,而不是 fstream?
【发布时间】:2020-12-16 00:44:57
【问题描述】:

我试图了解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 而不是 ofstream 时,失败位返回 1。

input.txt 就是这样:

Read and write to this file. 

What am I doing here?

This is not a good example of a file

【问题讨论】:

标签: c++ iostream


【解决方案1】:

我认为您描述的两种情况之间没有实际区别。

唯一的技术区别是ofstream 始终启用ios::out 标志,它将添加到您指定的任何标志中。而fstream 启用了ios::in 和ios::out 标志默认情况下,但将被您指定的任何标志覆盖。

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

但是,两个流都委托给std::filebuf,并且根据this reference 的std::filebuf::open(),out|app 和app 模式的行为方式完全相同——就好像使用了fopen(filename, "a"),因此它们将如果文件存在则“追加到文件”,如果文件不存在则“新建”。

【讨论】:

  • 当我将ofstream 行更改为fstream myfileI ("input.txt", ios::app|ios::out),而不是fstream myfileI ("input.txt", ios::app) 时,它正确地写入了文件。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-11-21
  • 2022-11-01
相关资源
最近更新 更多