C++ vector of ofstream, how to write to one particular element

微笑、不失礼 提交于 2019-12-08 10:44:36

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!