使用C 中的Freopen打开多个文件
opening multiple files using freopen in c++
我正在尝试多次使用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);
的stdin
。也,stdin
关闭文件后,现在正在悬挂指针。
以下是www.cplusplus.com的摘录:
如果指定了新的文件名,则该功能首先尝试关闭与流(第三参数)关联的任何文件并将其分解。然后,与该流是否成功关闭,Freopen独立于FreoPen打开文件名指定的文件,并像Fopen一样使用指定模式将其与流相关联。
。
关闭stdin
后,您应该使用fopen()
功能。
相关文章:
- .cpp和.h文件中的模板专用化声明
- 文本文件中的单词链表
- 如何将 txt 文件中的行分隔为组件C++
- C++-试图将函数指针推回到另一个CPP文件中的矢量时出错
- C++将文本文件中的数据读取到结构数组中
- 如何计算文件中的"columns"数?
- 如何使用单独文件中的派生类访问友元函数对象
- 如何在C++中确定文本文件中的元素是字符还是数字
- 在 .h 文件中的类中声明静态变量和在.cpp文件中声明"global"变量有什么区别
- 在gem5中打印文件中的所有cache_blocks
- 找不到QtResource文件中的文件
- 区分非成员函数和头文件中的成员函数
- 编辑文件中的文本
- 使用fstream对txt文件中的数字进行循环
- 调用 C 文件中的"C++"结构
- sqlite3 和生成文件中的链接出现问题
- 如何在 C++ 中将文件中的逗号分隔数字读取到数组中?
- 如何使用文件中的文本,例如变量
- 整数键映射到头文件中的成员函数指针
- C++ 使用存储在动态数组中的文本文件中的数据查找模式