c++ - fstream 的默认模式

标签 c++ file-handling tdm-gcc

我正在查看 SO 帖子 C++ file stream open modes ambiguity .我想知道fstream默认的文件打开方式。其中一个答案说,

What the above implies is that the following code opens the file with exactly the same open flags fstream f("a.txt", ios_base::in | ios_base::out); ifstream g("a.txt", ios_base::out); ofstream h("a.txt", ios_base::in);

因此,如果我理解正确,如果我创建了 fstream 对象,我应该能够读取或写入。

但是下面的代码没有向文件写入任何数据

fstream testFile1;
testFile1.open("text1.txt");
testFile1<<"Writing data to file";
testFile1.close();

但是添加下面给出的模式会创建带有数据“Writing data to file”的文本文件

testFile1.open("text1.txt", ios::out);

那么默认模式是否是实现定义的?我正在使用 TDM-GCC-64 工具链。

最佳答案

std::fstream 的默认模式是std::ios::in|std::ios::out。 ( Source )

您的代码不向 test1.txt 打印任何内容的原因是 std::ios::in|std::ios::out 模式执行如果文件不存在则不创建文件 ( Source: table on this page )。

您可以使用 std::ios::in|std::ios::app 模式,该模式将从头开始读取,从尾部开始写入,并将创建文件如果不存在。请注意,使用 app 模式,文件将在每次写入之前查找到末尾 ( Source )。

关于c++ - fstream 的默认模式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46948635/

相关文章:

c++ - 在 C++ 中,如何找到最大系统日期?

c++ - "error: taking address of temporary array"是什么意思?

c - 从 C 中的文本文件中查找并保存一个整数

ios - 附加到文本文件不起作用

java - 使用 JFileChooser 和文件处理

c - 有关于形状的事件吗?

c - 如何在 Windows 上为我的操作系统编译和链接 C 和 ASM

C++ 程序输出错误的数字

c++ - 在 Windows GUI 应用程序中使用 `main()` 而不是 `WinMain()` 时究竟会产生什么不良后果?

c++ - GDB 没有启动