How can I redirect stdout to some visible display in a Windows Application?

后端 未结 8 1301
时光取名叫无心
时光取名叫无心 2020-11-27 03:31

I have access to a third party library that does \"good stuff.\" It issues status and progress messages to stdout. In a Console application I can see these messages just f

相关标签:
8条回答
  • 2020-11-27 04:23

    You could do something like this with cout or cerr:

    // open a file stream
    ofstream out("filename");
    // save cout's stream buffer
    streambuf *sb = cout.rdbuf();
    // point cout's stream buffer to that of the open file
    cout.rdbuf(out.rdbuf());
    // now you can print to file by writing to cout
    cout << "Hello, world!";
    // restore cout's buffer back
    cout.rdbuf(sb);
    

    Or, you can do that with a std::stringstream or some other class derived from std::ostream.

    To redirect stdout, you'd need to reopen the file handle. This thread has some ideas of this nature.

    0 讨论(0)
  • 2020-11-27 04:24

    Thanks to the gamedev link in the answer by greyfade, I was able to write and test this simple piece of code

    AllocConsole();
    
    *stdout = *_tfdopen(_open_osfhandle((intptr_t) GetStdHandle(STD_OUTPUT_HANDLE), _O_WRONLY), _T("a"));
    *stderr = *_tfdopen(_open_osfhandle((intptr_t) GetStdHandle(STD_ERROR_HANDLE), _O_WRONLY), _T("a"));
    *stdin = *_tfdopen(_open_osfhandle((intptr_t) GetStdHandle(STD_INPUT_HANDLE), _O_WRONLY), _T("r"));
    
    
    printf("A printf to stdout\n");
    std::cout << "A << to std::cout\n";
    std::cerr << "A << to std::cerr\n";
    std::string input;
    std::cin >> input;
    
    std::cout << "value read from std::cin is " << input << std::endl;
    

    It works and is adequate for debugging. Getting the text into a more attractive GUI element would take a bit more work.

    0 讨论(0)
提交回复
热议问题