gpt4 book ai didi

c++ - 在 C++ 中使用 freopen 打开多个文件

转载 作者:行者123 更新时间:2023-11-30 05:06:27 26 4
gpt4 key购买 nike

我尝试多次使用 freopen() 来读取和关闭不同的文件。所以这是我在 main 函数中所做的:

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 读取没有问题)但是 while第二个循环似乎没有运行。输入文件格式正确,所以我不知道为什么 std::cin >> command 返回 false。

最佳答案

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

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

If a new filename is specified, the function first attempts to close any file already associated with stream (third parameter) and disassociates it. Then, independently of whether that stream was successfuly closed or not, freopen opens the file specified by filename and associates it with the stream just as fopen would do using the specified mode.

您应该在关闭stdin 之后使用fopen() 函数。

关于c++ - 在 C++ 中使用 freopen 打开多个文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47901702/

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