【问题标题】:Read Multiple Files In C++在 C++ 中读取多个文件
【发布时间】:2023-04-03 01:31:01
【问题描述】:

我正在尝试读取两个文件“ListEmployees01.txt”和“ListEmployees02.table”。但是程序只读取“ListEmployees01.txt”文件,cout 就是来自那个文件。

#define _CRT_SECURE_NO_WARNINGS

#include <iostream>
#include <string>
using namespace std;

int main()
{
    freopen("ListEmployees01.txt", "r", stdin);
    string s;
    while (getline(cin, s))
        cout << s<<endl;
    fclose(stdin);
    freopen("ListEmployees02.table", "r", stdin);
    while (getline(cin, s))
        cout << s<<endl;

}

【问题讨论】:

  • 为什么要使用freopen 以C 流stdin 的形式打开文件,而不是创建std::ifstream C++ 对象来读取文件?
  • 两个freopen 表达式都尝试分配给标准输入,但不能保证可分配。
  • 谢谢。我将使用 ifstream

标签: c++ freopen


【解决方案1】:

您可以使用std::ifstream 而不是更改std::cin 的行为。

【讨论】:

  • 我可以使用 freopen 代替 ifstream 吗?
  • @DuongPhan 为什么?这应该解决什么问题?
  • 谢谢。我只是更喜欢 freopen ... 在这个问题中,我将使用 ifsrtream
【解决方案2】:

我将使用fstream 执行以下操作

#include <fstream>

void readAndPrint(const char *filename) {

    std::ifstream file(filename);

    if (file.is_open()) {

        std::string line;
        while (getline(file, line)) {
            printf("%s\n", line.c_str());
        }
        file.close();

    }

}

int main() {

    readAndPrint("ListEmployees01.txt");
    readAndPrint("ListEmployees02.table");

    return 0;
}

如果您必须使用freopen,请查看man freopen,或C++ 参考http://www.cplusplus.com/reference/cstdio/freopen

【讨论】:

    【解决方案3】:

    在您的情况下,对于第二个文件,您使用的标准输入已经被下一行关闭,因此它是文件关闭后的悬空指针

    fclose(stdin)

    您可以对第二个文件使用 fopen 而不是 freopen。

    请查看 www.cplusplus.com/reference/cstdio/freopen/ 中的以下段落

    如果指定了新文件名,函数首先尝试关闭 任何已与流关联的文件(第三个参数)和 解除关联。然后,无论该流是否是 成功关闭与否,freopen打开指定的文件 文件名并将其与流相关联,就像 fopen 一样 使用指定的模式。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-03-22
      • 2014-03-19
      • 1970-01-01
      • 2014-04-21
      • 1970-01-01
      • 2019-08-04
      相关资源
      最近更新 更多