为什么std::fstream不能向文件中写入内容?

15

我在使用fstreamoftream时发现它们的行为不同,但是我无法解释。

当我使用fstream时,什么都没有发生,也就是说没有文件被创建

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

但是当我将fstream更改为ofstream时,它起作用了。

为什么?

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


3
可以。缓冲?我认为我们需要提供一个完整的 [mcve] 示例。 - Martin Bonner supports Monica
1
我只有这段代码的一个函数,但它不起作用。我没有其他要写的了。MVS2015。 - Narek
5
你有检查过它是否已经打开了吗?比如像这样:if (!file) cout <<"错误";。你尝试过使用 std::ofstream file(...) 吗? - Bob__
3
当然,你需要写更多内容:这两行无法编译。你至少需要一个头文件来定义std :: fstream,并且需要一个main函数。 - Martin Bonner supports Monica
1
可能是重复的问题:std::fstream不创建文件 - LogicStuff
显示剩余2条评论
1个回答

29

ios_base::in 要求文件存在.

如果你提供仅有 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                    |
+--------------------+-------------------------------+-------------------------------+

提示:

一些基本的错误处理可能在理解发生了什么方面也会证明有用:

#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>

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接