Question

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();
 }
}
Was it helpful?

Solution

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());
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top