问题
To avoid continuously opening and closing multiple files that I am writing to, I am attempting to use a vector of ofstream objects. My code looks like the following so far:
std::vector<shared_ptr<ofstream>> filelist;
void main()
{
for(int ii=0;ii<10;ii++)
{
string filename = "/dev/shm/table_"+int2string(ii)+".csv";
filelist.push_back(make_shared<ofstream>(filename.c_str()));
}
}
I am using a vector of ofstream pointers because ofstream doesn't have a copy constructor. Furthermore, I'm using a shared pointer because that is supposed to be more robust against memory leaks.
The above successfully creates the files I want in the target directory. If I want to close the files, I can do something like filelist[5]->close();
The only part I'm not sure about is how I actually write to each of these files. Typically, for a single file, I do something like:
ofstream fout;
fout.open("myfile.txt");
fout<<"some text"<<endl;
What is the equivalent of << that I want to use in this case?
回答1:
Try this:
for (auto& stream : filelist)
{
*stream << "some text" << std::endl;
}
回答2:
You need either an ostream
or ostream&
.
filelist[i]
is a shared_ptr<ostream>
which you can in this case think of as basically an ostream*
. This means that *filelist[i]
gives you an ostream&
(via the operator* overload). So, you would use something like *filelist[i] << "some text << std::endl;
来源:https://stackoverflow.com/questions/15737023/c-vector-of-ofstream-how-to-write-to-one-particular-element