简体   繁体   中英

C++: file output with a random name

I'm new to C++ so this might be a very naive question. I'm trying to output data to a file by calling a function from my main file. I am calling this function multiple times within my main functions and that's why I need to switch on the append mode for writing the files. This line of code writes my output file and works fine:

ofstream outFile("result_col2.plt",ios::app);
.
.
outFile.close();

However, I want to make my output file's name random, and I am trying this:

int number = 1; // let's say
ostringstream convert;
convert << number;
string iLevel_str = convert.str();
string fname = "result_col2" + iLevel_str + ".plt";
ofstream outFile(fname.c_str(),ios::app);
.
.
outFile.close();

But when I do this, my data files are becoming double the size after every run. Why is it that it doesn't work in the latter case, but works well in my previous case? Any suggestions?

To make it more understandable, the file named "result_col2.plt" remains the same size after every run of the main function. Whereas the file named "result_col21.plt" is doubling in size (first run - 85 kb, then 170 kb, and so on.)

除非您更改int number = 1,否则它将不断打开并不断添加result_col21.plt,因此,加倍操作需要进行for循环,每次迭代均需递增该数字

If you need just a random file name you can use std::tmpnam() standard function, but it will generate random file name located in system "temp" directory.

For details please refer to: http://en.cppreference.com/w/cpp/io/c/tmpnam

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM