使用C 中的Freopen打开多个文件

opening multiple files using freopen in c++

本文关键字:文件 中的 Freopen 使用      更新时间:2023-10-16

我正在尝试多次使用freopen()读取和关闭不同的文件。所以这是我在主要功能中所做的:

if (argc != 5) {
    std::cerr << "Wrong format of arguments given." << endl;
    return -1;
}
std::string command, command2;
freopen(argv[1], "r", stdin);
// do something...
fclose(stdin);
freopen(argv[2], "r", stdin);
freopen(argv[3], "w", stdout);
while (std::cin >> command) {
    std::cin >> command2;
    // run some function...
}
fclose(stdin);
fclose(stdout);

,但事实证明,第一部分// do something...可以正常工作(从std::cin读取而没有问题),但是第二部分的循环似乎没有运行。输入文件是正确格式的,所以我不知道std::cin >> command为什么返回false。

freopen(argv[2], "r", stdin);行中,您正在尝试重新打开stdin。但是您已经在此之前关闭了fclose(stdin);stdinstdin关闭文件后,现在正在悬挂指针

以下是www.cplusplus.com的摘录:

如果指定了新的文件名,则该功能首先尝试关闭与流(第三参数)关联的任何文件并将其分解。然后,与该流是否成功关闭,Freopen独立于FreoPen打开文件名指定的文件,并像Fopen一样使用指定模式将其与流相关联。

关闭stdin后,您应该使用fopen()功能。