c++ - 重复使用相同的 ofstream 对象

标签 c++ ofstream

我想知道是否可以使用相同的 ofstream 对象打开多个文件?

string fileName = "transaction" + to_string(nbFile) + ex;
ofstream fs(fileName.c_str());
fs << "foo";

nbFile++;
fs.close();

string fileName = "transaction" + to_string(nbFile) + ex;
ofstream fs(fileName.c_str());
fs << "foo2"

如果我执行此代码,将创建第二个文件。如果我们可以使用相同的流重新打开文件,我在 MSDN 文档中找不到。

最佳答案

I would like to know if its possible to open multiple files with the same ofstream object ?

是的。方法如下:

string fileName = "transaction" + to_string(nbFile) + ex;
ofstream fs(fileName.c_str());
fs << "foo";

nbFile++;
fs.close();

fileName = "transaction" + to_string(nbFile) + ex;

// Not this.
// ofstream fs(fileName.c_str());

// This
fs.open(fileName.c_str());

fs << "foo2"

关于c++ - 重复使用相同的 ofstream 对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28750071/

相关文章:

c++ - 如何使用指针从不同的函数访问局部变量?

c++ - 如何在 C++ 中打印\"

c++ - 将 boost::multiprecision 数据类型写入二进制文件

c++ - 在不存在的目录中打开文件 c 与 c++

c++ - 如何在目录中以特定格式获取行的特定部分?

c++ - C/C++ - 对其他人隐藏 C 或 C++ 函数代码

堆栈上的 C++ 实例变量存储为指针

c++ - GCC:在 "control reaches end of non-void function"中断编译

c++ - N 元树级别遍历错误 (C++)

c++ - Ofstream 比 cout 快? ||存储速度快于视觉输出