流迭代器的重用

Reuse of the stream iterators

本文关键字:迭代器      更新时间:2023-10-16

我有一个文件需要在运行时多次打开。每次都会将一些文本附加到文件中。这是代码:

    ofstream fs;
    fs.open(debugfile, fstream::app);
    ostream_iterator<double> output(fs, " ");
    copy(starting_point.begin(), starting_point.end(), output);
    ...
    fs.open(debugfile, fstream::app);
    ostream_iterator<double> output1(fs, " ");
    copy(starting_point.begin(), starting_point.end(), output1);

我的问题是,每次打开文件时,我是否可以使用一个流迭代器"输出",例如某种清理方法?

感谢

您可以使用以下代码:

ofstream fs;
fs.open(debugfile, fstream::app);
ostream_iterator<double> output(fs, " ");
copy(starting_point.begin(), starting_point.end(), output);
...
fs.open(debugfile, fstream::app);
output = ostream_iterator<double>(fs, " ");
copy(starting_point.begin(), starting_point.end(), output1);

这里使用相同的变量output来存储迭代器,但迭代器本身是从头开始创建的,并使用operator =分配给该变量。

对我来说,没有什么可以做的(apprt重新分配值)来解决您的问题。

只是不要忘记在重新打开流之前关闭并清除它:

std::ofstream file("1");
// ...
file.close();
file.clear(); // clear flags
file.open("2");

from:C++我可以重用fstream来打开和写入多个文件吗?