0

我正在尝试动态创建文件,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();
 }
}
4

1 回答 1

5

如果您的意思是使用在运行时创建的名称,那么可以,但是您必须以有效的方式构建您的名称。例如(在 之后#include <sstream>):

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

outfile.open(fname.str().c_str());
于 2011-01-05T23:13:43.110 回答