views:

5855

answers:

7

If I have a native C++ windows program (i.e. the entry point is WinMain) how do I view output from console functions like std::cout?

+1  A: 

Since there's no console window, this is impossible difficult. (Learn something new every day - I never knew about the console functions!)

Is it possible for you to replace your output calls? I will often use TRACE or OutputDebugString to send information to the Visual Studio output window.

Mark Ransom
Actually, it is possible, but tricky, to get a console window for programs using the WinMain() entry point instead of main().
Chris Charabaruk
+1  A: 

This link might offer some help, depending on whether you are trying to read your output, or another applications:

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

Mark Ingram
+1  A: 

Don't quote me on this, but the Win32 console API might be what you're looking for. If you're just doing this for debugging purposes, however, you might be more interested in running DebugView and calling the DbgPrint function.

This of course assumes its your application you want sending console output, not reading it from another application. In that case, pipes might be your friend.

Chris Charabaruk
+6  A: 

Check out Adding Console I/O to a Win32 GUI App. This may help you do what you want.

If you don't have, or can't modify the code, try the suggestions found here to redirect console output to a file.

luke
Dustin Getz
Good link. The gamedev.net forums have always provided me with a wealth of information.
luke
+1  A: 

You can also reopen the cout and cerr streams to output to a file as well. The following should work for this:

#include <iostream>
#include <fstream>

int main ()
{
std::ofstream file;
file.open ("cout.txt");
streambuf* sbuf = std::cout.rdbuf();
std::cout.rdbuf(file.rdbuf());
//cout is now pointing to a file
return 0;
}
workmad3
A: 

creating a pipe, execute the program console CreateProcess() and read with ReadFile() or writes in console WriteFile()

    HANDLE hRead ; // ConsoleStdInput
    HANDLE hWrite; // ConsoleStdOutput and ConsoleStdError

    STARTUPINFO           stiConsole;
    SECURITY_ATTRIBUTES   segConsole;
    PROCESS_INFORMATION   priConsole;

    segConsole.nLength = sizeof(segConsole);
    segConsole.lpSecurityDescriptor = NULL;
    segConsole.bInheritHandle = TRUE;

if(CreatePipe(&hRead,&hWrite,&segConsole,0) )
{

    FillMemory(&stiConsole,sizeof(stiConsole),0);
    stiConsole.cb = sizeof(stiConsole);
GetStartupInfo(&stiConsole);
stiConsole.hStdOutput = hWrite;
stiConsole.hStdError  = hWrite;
stiConsole.dwFlags    = STARTF_USESHOWWINDOW | STARTF_USESTDHANDLES;
stiConsole.wShowWindow = SW_HIDE; // execute hide 

    if(CreateProcess(NULL, "c:\\teste.exe",NULL,NULL,TRUE,NULL,
      NULL,NULL,&stiConsole,&priConsole) == TRUE)
    {
        //readfile and/or writefile
}

}