我想知道是否可以使用相同的 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/