c++stdinfreopen

opening multiple files using freopen in c++


I'm trying to use freopen() multiple times to read and close different files. So here's what I did inside my main function:

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

But it turns out that the first part, // do something..., works fine (reads from std::cin without a problem) but the while loop in the second doesn't seem to run. The input files are of correct formats, so I don't know why std::cin >> command returns false.


Solution

  • In line freopen(argv[2], "r", stdin); you are trying to reopen stdin. But you have already closed stdin in line fclose(stdin); just before that. Also, stdin is now dangling pointer after closing the file.

    Following is an extract from 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.

    You should use fopen() function after closing stdin.