我正在查看 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/