Duong Phan
Duong Phan

Reputation: 341

Read Multiple Files In C++

I am trying to read two files "ListEmployees01.txt" and "ListEmployees02.table". But the program reads only the "ListEmployees01.txt" file and cout is just from that file.

#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;

}

Upvotes: 0

Views: 1017

Answers (3)

Abhishek Chandel
Abhishek Chandel

Reputation: 1354

In your case , in the case of second file you are using the stdin which is already closed by below line , hence it is a dangling pointer after file close

fclose(stdin)

You can use fopen instead of freopen for the second file.

Please check the below paragraph from 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.

Upvotes: 1

Kristof Gilicze
Kristof Gilicze

Reputation: 530

I would do the following using 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;
}

If you must use freopen, then have a look at man freopen, or the C++ reference http://www.cplusplus.com/reference/cstdio/freopen .

Upvotes: 1

openingnow
openingnow

Reputation: 134

You can use std::ifstream instead of changing std::cin's behavior.

Upvotes: 2

Related Questions