C++读取多个文件

Read Multiple Files In C++

我正在尝试读取两个文件 "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;

}

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

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

fclose(stdin)

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

请检查以下来自 www.cplusplus 的段落。com/reference/cstdio/freopen/

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.

我会使用 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