how do I write to stdout from an MFC program?

2020-02-09 09:32发布

问题:

MFC programs can't normally write to stdout. MFC does something weird with the stdout/stdin pipes during startup and anything you write (for example doing a printf("hello");) just goes to /dev/null.

Does anyone know how to successfully write to stdout from an MFC program?

Thanks for reading.

回答1:

Use AllocConsole function to create a console for writing into. The following article explains how to use it to print to console.

Creating a console for your MFC app's debug output

Dont forget to FreeConsole once you're done with it.



回答2:

Here's a one-liner that I found online a while back that attaches stdout to a console in MFC. This allows printf and cout to write to the console window of the current process. I never looked into how it works, so if you need a cerr or cin version you're on your own.

AllocConsole();
*stdout = *_tfdopen(_open_osfhandle((intptr_t) GetStdHandle(STD_OUTPUT_HANDLE), _O_APPEND), _T("a"));


回答3:

This will attach to the calling console window, if one is present. GotConsoleAttach will be FALSE when the application wasn't called from a console.

GotConsoleAttach = FALSE;    
if (AttachConsole(ATTACH_PARENT_PROCESS))
{   
    int osfh = _open_osfhandle((intptr_t) GetStdHandle(STD_OUTPUT_HANDLE), 8);
    if ((HANDLE)osfh != INVALID_HANDLE_VALUE)
    {
        *stdout = *_tfdopen(osfh, _T("a"));
        GotConsoleAttach = TRUE;
    }
}


回答4:

If you are just looking for output to the debug window, you can use TRACE.

TRACE("This is a debug string of text in MFC");

I do this when I am quickly testing something and don't want to use dialog boxes, like MessageBox("text").



回答5:

After spending an entire day trying to make my MFC program to print using printf() and cout I finally found a solution and decide to post it here to help who wants to print at MFC...

void EnablePrintfAtMFC()
{
    if (AttachConsole(ATTACH_PARENT_PROCESS))
    {
        FILE* pCout;
        freopen_s(&pCout, "CONOUT$", "w", stdout);
        std::cout.clear();
        std::wcout.clear();
    }
}

Just call the above function in some place of your program, and after that you will be able to use printf() and cout...

EnablePrintfAtMFC();
printf("Hello world!\n");
std::cout << "It works!" << endl;


标签: c++ mfc stdout