为什么std :: fstream没有写入文件?

时间:2016-09-05 07:41:38

标签: c++

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

当我使用oftream时,没有任何反应,即没有创建文件

fstream

但是当我将int main() { std::fstream file("myfile.txt"); file << "some text" << std::endl; return 0; } 更改为fstream时,它可以正常工作。

为什么?

oftream CTOR的第二个参数是fstream,这让我觉得文件是以读写模式打开的,对吗?

1 个答案:

答案 0 :(得分:27)

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>