Search code examples
c++binarystdinmingw32wine

freopen doesn't work for C stdin


While executing the following code:

#include <iostream>
using std::cout;

#include <cstdio>
/* stdin
   stdout
   FILE
   freopen */

int main() {
    for (FILE* f : {stdin, stdout})
        if (nullptr == freopen(nullptr, (f == stdin) ? "rb" : "wb", f))
            cout << f << '\n';
}

... I get the following output:

0x7edde180

... which means that freopen(nullptr, "rb", stdin) returned nullptr, failing.

Am I doing anything wrong?

Compiler: i586-mingw32msvc-g++ on the GNU OS

Environment: wine (x86)


Solution

  • http://msdn.microsoft.com/en-us/library/wk2h68td.aspx

    If path, mode, or stream is a null pointer, or if filename is an empty string, these functions invoke the invalid parameter handler, as described in Parameter Validation. If execution is allowed to continue, these functions set errno to EINVAL and return NULL.

    In short, it looks like the MSVC++ implementation of freopen does not allow for a NULL pathname.