【问题标题】:Iteratively accessing and writing to multiple files using ofstream使用 ofstream 迭代访问和写入多个文件
【发布时间】:2018-04-18 07:30:51
【问题描述】:

我有一对头文件。在 IsingModel.h 中,我公开声明:

ofstream logfile1;
ofstream logfile2;

然后打开相关文件(logfile1和logfile 2名称不同)我使用:

do {
        name2.str(""); //reset name stringstream
        n++; //increase n value
        name2 << "output_" << gridSize << "_" << seed << "_" << n << "_eqmCalc.txt"; //stream created

    } while (if_exist(name2.str())); //test if file already exists
    logfile2.open(name2.str());

在创建文件时起作用。然后,在整个代码中,我使用 ofstreams 对文件进行操作,例如:

logfile1 << counter << " " << calcM() << " " << calcE() << endl;

这对于每个文件独立的操作来说很好,但是当我调用析构函数时,我想将相同的标准信息写入每个文件。为此,我正在尝试迭代写入文件,但它似乎不起作用:

void IsingSystem::test() {
for (int i = 1; i = 2; i++) {
    if (ofstream("logfile" + to_string(i)).is_open); {
        ofstream("logfile" + to_string(i)) << "success" << endl;
        }
    }
}

这会创建名为 logfile1 和 logfile2 的文件。作为替代方案,我尝试创建一个 ofstreams 数组:

void createFileHandles() {
    const int count = 2;         
    std::ofstream logfile[count];     
}

但是,我不知道如何在函数之间正确传递。

处理流的正确方法是什么,以便我可以打开多个文件,同时向它们写入不同的指令,但也有一些同时发生在两个文件上的操作?

【问题讨论】:

  • 使用ofstream的数组。您的函数可以接受 ofstream 作为参数并对其进行处理。使用函数(logfile [index])传入适当的 ofstream。显然你的数组应该在调用的范围内声明。

标签: c++ file loops


【解决方案1】:

你可以有一个ofstream的向量

vector<ofstream> ofstreams(2);
//fill vec
for (int i = 0; i < 2; i++)
{
    if (ofstreams[i].is_open);
    {
        ofstreams[i]<< "success" << endl;
    }
}

然后您可以将ofstreams 传递给函数。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-05-20
    • 1970-01-01
    • 2014-08-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多