开发者

Doesn't fstream support dynamic creation of files

开发者 https://www.devze.com 2023-02-02 10:39 出处:网络
I\'m trying to create files dynamically and it seems like there is no way with fstream. Is there actually any?

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


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());
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号