Reputation: 15
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.)
Upvotes: 0
Views: 224
Reputation: 1023
unless you change that int number =1 it will keep opening and appending result_col21.plt over and over hence the doubling you need to do a for loop incrementing the number every iteration
Upvotes: 1
Reputation: 116
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
Upvotes: 0