我正在尝试动态创建文件,似乎fstream无法实现。真的有吗?

#include <iostream>
#include <fstream>
using namespace std;

int main () {

for (int i = 0; i<2; ++i){
 std::ofstream outfile
 outfile.open ((char)i+"sample_file.txt"); // something like this. numbers appended to the filename
 outfile << i;
 outfile.close();
 }
}

最佳答案

如果您的意思是在运行时创建一个名称,则可以,但是您必须以一种有效的方式来建立您的名称。例如。 (在#include <sstream>之后):

std::ostringstream fname;
fname << "sample_file_" << i << ".txt";

outfile.open(fname.str().c_str());

关于c++ - fstream不支持动态创建文件,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/4610142/

10-13 05:05