我在Friend
与fstream
之间的行为不同,我无法解释。
当我使用oftream
时,没有任何反应,即没有创建文件:
fstream
但是当我将int main()
{
std::fstream file("myfile.txt");
file << "some text" << std::endl;
return 0;
}
更改为fstream
时,它可以正常工作。
为什么?
oftream
CTOR的第二个参数是fstream
,这让我觉得文件是以读写模式打开的,对吗?
答案 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>