0x0
0x0

Reputation: 3075

Doesn't fstream support dynamic creation of files

I'm trying to create files dynamically and it seems like there is no way with fstream. Is there actually any?

#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();
 }
}

Upvotes: 0

Views: 1103

Answers (1)

CB Bailey
CB Bailey

Reputation: 792487

If you mean with a name created at run time, then yes, but you have to build your name in a valid way. E.g. (after #include <sstream>):

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

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

Upvotes: 5

Related Questions