Share via


Windows API - How can I get printf() to work in this console example?

Question

Thursday, August 3, 2017 5:03 AM

I'd like to try out implementing a console using Windows API. I copied a code example from this blog, and added a message loop so that the console window would stay open until I explicitly closed it.

I tried out the WriteFile function with the 'handle_out' variable which seems to be a handle to the console's output stream or something, and that worked fine. However, unlike the blog said, the printf() function I used didn't print anything.

How could I get printf() to work in the example below? If it helps, I copied it as a C file. I'm not familiar with the code involving 'stdin' and 'stdout', but I'm guessing it has to do with connecting the handles of the console's streams to the standard streams.

#include <stdio.h>
#include <io.h>
#include <fcntl.h>
#include <windows.h>


int APIENTRY WinMain(HINSTANCE hInstance,
    HINSTANCE hPrevInstance,
    LPSTR     lpCmdLine,
    int       nCmdShow)
{
    MSG Msg;
    AllocConsole();

    HANDLE handle_out = GetStdHandle(STD_OUTPUT_HANDLE);
    int hCrt = _open_osfhandle((long)handle_out, _O_TEXT);
    FILE* hf_out = _fdopen(hCrt, "w");
    setvbuf(hf_out, NULL, _IONBF, 1);
    *stdout = *hf_out;

    HANDLE handle_in = GetStdHandle(STD_INPUT_HANDLE);
    hCrt = _open_osfhandle((long)handle_in, _O_TEXT);
    FILE* hf_in = _fdopen(hCrt, "r");
    setvbuf(hf_in, NULL, _IONBF, 128);
    *stdin = *hf_in;


    //
    //added write tests and message loop below
    WriteFile(handle_out, "This is a test sentence.\n", 25, NULL, NULL);
    WriteFile(handle_out, "This is a test sentence.(2)\n", 28, NULL, NULL);
    printf("This is a test sentence.(3)");

    while (GetMessage(&Msg, NULL, 0, 0) > 0) 
    {
        TranslateMessage(&Msg);
        DispatchMessage(&Msg);
    }
}

All replies (2)

Thursday, August 3, 2017 9:36 AM âś…Answered | 1 vote

See the code snippet at https://social.msdn.microsoft.com/Forums/en-US/653d3703-feae-4537-b1c6-bd548057d0c3/how-to-get-output-on-command-prompt-if-i-run-mfc-mdi-application-through-cmd-prompt?forum=vcgeneral

The snippet works with AllocConsole also, but you would remove the call to FreeConsole.


Thursday, August 3, 2017 5:26 PM

Thanks. AllocConsole worked in WinMain. Found AttachConsole(ATTACH_PARENT_PROCESS) didn't work, but that makes sense, since I only have one process with no parent process. 

Edit: I was trying to look into the "CONIN$" and "CONOUT$" strings to understand the snippet, looked mysterious. Found info. from CreateFile() documentation, thought it'd be helpful to note it here.