【问题标题】:Why doesn't std::fstream write to a file? [closed]为什么 std::fstream 不写入文件? [关闭]
【发布时间】:2016-09-05 07:41:37
【问题描述】:

fstreamoftream 之间的行为不同,我无法解释。

当我使用fstream 时,什么都没有发生,即没有文件被创建

int main()
{
    std::fstream file("myfile.txt");
    file << "some text"  << std::endl;
    return 0;
}

但是当我将fstream 更改为oftream 时,它可以工作。

为什么?

fstream CTOR 的第二个参数是ios_base::openmode mode = ios_base::in | ios_base::out,这让我觉得文件是以读写模式打开的,对吧?

【问题讨论】:

  • 应该可以。缓冲?我认为我们需要一个完整的minimal reproducible example
  • 我只有一个带有此代码的功能,但它不起作用。我没有什么可写的了。 MVS2015.
  • 你检查它是否打开了吗?比如if (!file) cout &lt;&lt;"Error";。你试过std::ofstream file(...吗?
  • 当然,您还有更多内容要写:这两行将无法编译。你至少需要一个头文件来定义 std::fstream 并且你需要一个main 函数。

标签: c++


【解决方案1】:

ios_base::in requires the file to exist.

如果您提供 ios_base::out,则只有在该文件不存在时才会创建该文件。

+--------------------+-------------------------------+-------------------------------+
| openmode           | Action if file already exists | Action if file does not exist |
+--------------------+-------------------------------+-------------------------------+
| in                 | Read from start               | Failure to open               |
+--------------------+-------------------------------+-------------------------------+
| out, out|trunc     | Destroy contents              | Create new                    |
+--------------------+-------------------------------+-------------------------------+
| app, out|app       | Append to file                | Create new                    |
+--------------------+-------------------------------+-------------------------------+
| out|in             | Read from start               | Error                         |
+--------------------+-------------------------------+-------------------------------+
| out|in|trunc       | Destroy contents              | Create new                    |
+--------------------+-------------------------------+-------------------------------+
| out|in|app, in|app | Write to end                  | Create new                    |
+--------------------+-------------------------------+-------------------------------+

PS:

一些基本的错误处理也可能有助于理解正在发生的事情:

#include <iostream>
#include <fstream>

int main()
{
  std::fstream file("triangle.txt");
  if (!file) {
    std::cerr << "file open failed: " << std::strerror(errno) << "\n";
    return 1;
  }
  file << "Some text " << std::endl;
}

输出:

 C:\temp> mytest.exe
 file open failed: No such file or directory

 C:\temp>

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-02-08
    • 2013-01-18
    • 1970-01-01
    相关资源
    最近更新 更多