> I would like to have all files opened permanently.
As far as possible, limit the life-time of objects to the period when the object is required.
In this case: even if the implementation allows it, do not keep hundreds of files open simultaneously.
> Until now I have for output one single ofstream and I always open, write and close the right file.
> The big problem is the .open() operation which always takes a extremely long time
This is implementation dependent: creating a different object of type
std::ofstream for each file could be faster.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
|
#include <iostream>
#include <fstream>
#include <string>
int main()
{
std::ifstream input_file( __FILE__ ) ; // this file
int n = 0 ; // output file sequence number
const std::string file_name_prefix = "output_" ;
const std::string file_name_suffix = ".txt" ;
std::string line ;
while( std::getline( input_file, line ) )
{
// a different ofstream object for each file
std::ofstream output_file( file_name_prefix + std::to_string(++n) + file_name_suffix ) ;
output_file << line << '\n' ;
}
}
|
If that is not fast enough, work with two (just two)
std::ofstream objects which you use in a round-robin manner.
While writing to one
std::ofstream, close and reopen (for the next file) the other
std::ofstream asynchronously.
See:
std::async() http://en.cppreference.com/w/cpp/thread/async