Reputation: 43
I want to create some file inside two loops and fill out them without closing the file inside the first and second loop.
Here you can find what I mean of this question by looking at this part of a code, and it doesn't work ... of course, it creates 100 files but the problem is that each file just holds the last iteration of the first loop while I want each file to write the whole iteration of the first loop.
ofstream fout;
for(int t = 0; t < N; t++){
for(int e = 0; e < 100; e++){
fout.open("myfile_"+strcpp(e)+".txt");
fout << t << psi[e] << endl;
}
}
fout.close();
where the function strcpp(e)
is given by
template <class T>
string strcpp(T value){
ostringstream out;
out << value;
return out.str();
}
Upvotes: 0
Views: 110
Reputation: 26
Every time you call:
fout.open(...);
The whole contents of the file before opening it are erased. Since you open each file many times you are constantly erasing anything that you had written to it before you write the next line. This is why the last write of your outer for loop is the only thing in each file. We can fix this by specifying we want to append to the file we are opening. std::ofstream::open() takes a second optional argument that specifies the mode. You can set the mode to append whatever you write in the file to the end of what is already in there instead of erasing the original file contents. Ex:
fout.open(my_file_name, ios::app);
Although a better solution might be to just switch in your inner and outer for loop. Then you open each file before the start of the inner for loop, do all the writes to that one file, then close that file and move on to the next one. This way you don't have to open each file many, many times.
Upvotes: 1