问题描述
为了避免连续打开和关闭我写入的多个文件,我试图使用一个ofstream对象的向量。我的代码到目前为止如下:
std :: vector< shared_ptr< ofstream>文件列表
void main()
{
for(int ii = 0; ii {
string filename =/ dev / shm / table _+ int2string(ii)+。csv;
filelist.push_back(make_shared< ofstream>(filename.c_str()));
}
}
指针,因为stream没有复制构造函数。此外,我使用一个共享指针,因为它应该是更加健壮的内存泄漏。
上面的成功创建了我想要的目标目录中的文件。如果我想关闭文件,我可以做一些像filelist [5] - > close();
我不知道的唯一部分是如何实际写入每个这些文件。通常,对于单个文件,我做类似于:
ofstream fout;
fout.open(myfile.txt);
fout<<some text<< endl;
相当于<<
pre>
for(auto& stream:filelist)
{
* stream< 一些文本< std :: endl;
}
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?
Try this:
for (auto& stream : filelist)
{
*stream << "some text" << std::endl;
}
这篇关于ofstream的C ++向量,如何写入一个特定的元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!