gpt4 book ai didi

c++ - 使用 C++ 的文件 I/O 同时打开两个文件

转载 作者:塔克拉玛干 更新时间:2023-11-03 01:55:54 25 4
gpt4 key购买 nike

难道不能使用不同的流同时打开两个文件吗?我正在尝试写入两个 ofstreams,一个有一个变量文件名,每次循环迭代时都会更改,另一个有一个固定的文件名,我正在写入的数据将在循环的每次迭代中附加。演示:

ofstream file_variable_name;
ofstream file_to_be_appended;

{ //THIS IS A LOOP, variable_name changes at every iteration

file_variable_name.open(variable_name.c_str(), ios::out);
file_to_be_appended.open("fixed name", ios::out | ios::app);

//Do lots of things here, make data ready to be written to file

file_variable_name << "write something" << endl;
file_to_be_appended << "write same as above, but this is to be appended" << endl;

file_variable_name.close();
file_to_be_appended.close();
}

不知何故,我什至无法创建第二个文件,更不用说打开和附加了。我也可以发送完整的代码(大约 1000 行左右,需要截断),但我认为以上内容可以解释我正在尝试做的事情,任何逻辑缺陷对专业人士来说都是显而易见的。

提前感谢所有建议!

最佳答案

你让它变得比实际更难。通常不需要使用 .open() 和 .close() 方法,也不需要一直重新打开同一个文件:

#include <fstream>

int main(int argc, char *argv[])
{
std::ofstream file_to_be_appended("fixed name");

char const *list[] = {"a", "b", "c"};
for (auto s : list) { // My compiler doesn't have generalized initializer lists yet
std::ofstream file_variable_name(s);

file_variable_name << "write something\n";
file_to_be_appended << "write same as above, but this is to be appended\n";
}
}

关于c++ - 使用 C++ 的文件 I/O 同时打开两个文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11480195/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com