简体   繁体   中英

Redirecting standard output - Switched from VS2013 to VS2017, exception on writing

I've recently switched a project from using the VS2013 compiler to VS2017, and now the following code appears not to be working:

#include <windows.h>
#include <Fcntl.h>
#include <io.h>
#include <iostream>
#include <exception>

if( RedirectOutput )
{
    //Setup stdout
    HANDLE handle_stdout = GetStdHandle( STD_OUTPUT_HANDLE );

    int fileDesc_stdout = _open_osfhandle( (long)handle_stdout, _O_TEXT );

    if( fileDesc_stdout == -1 )
    {
        throw std::exception( "fileDesc_stdout is not valid" );
    }

    FILE* new_stdout = _fdopen( fileDesc_stdout, "w" );

    if( !new_stdout )
    {
        throw std::exception( "new_stdout is not valid" );
    }

    FILE old_stdout = *stdout;
    *stdout = *new_stdout;

    std::cout.clear();

    std::cout << "Output Redirected!\n";
}

This code is intended to redirect standard output to a console window, either the one that kicked off the current process or a console that is created via AllocConsole. (I've added the last line for testing purposes.)

The first time writing to cout occurs, the following exception is thrown (it otherwise doesn't write output and fails silently from then on):

Debug Assertion Failed!

Program: w:\\build\\MyApp.exe File: minkernel\\crts\\ucrt\\src\\appcrt\\stdio_flsbuf.cpp Line: 26

Expression: ("inconsistent IOB fields", stream->_ptr - stream->_base >= 0)

For information on how your program can cause an assertion failure, see the Visual C++ documentation on asserts.

(Press Retry to debug the application)

I can see that stdout is coming from corecrt_wstdio.h, but when I insert a breakpoint and add a watch, it says that the stdout is undefined, so I can't check the value.

Any ideas?

So I searched around a bit and found this post on SO.

Essentially, all of the code I posted can be replaced with the following:

freopen("CONOUT$", "w", stdout);

The first parameter of freopen is a filename, so I wonder if CONOUT$/CONIN$ represent an actual file, or if the function treats that input as a special case.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM