Internally capture/redirect stdout?

后端 未结 4 1456
梦如初夏
梦如初夏 2020-12-18 07:32

This seems like a bit of a computing systems 101 question, but I\'m stumped.

I am integrating existing code from C/C++ project A into my own project B. Both A and B

相关标签:
4条回答
  • 2020-12-18 07:49

    Before you printf(), you could close fd 1, and dup2() a pipe that you've created into fd 1.

    0 讨论(0)
  • 2020-12-18 07:59

    You can use freopen to change the descriptor.

    #include<stdio.h>
    
    main(int argc, char** argv) {
        FILE *fp = freopen("output.txt", "w", stdout);
        printf("Hello\n");
        fclose(fp);
    }
    

    If you run that you'll see the printf output in output.txt and nothing will go to your screen.

    You can now open the file to read the data or you could even mmap it into your memory space and process it that way.

    0 讨论(0)
  • 2020-12-18 08:02

    Not to mention: there is now a handy U-Streams C source code library that makes redirecting stdout and stderr quite trivial. And you can even redirect them very easily to multiple destinations. And, you can create your own streams besides that can be used in exactly the same way stdout and stderr behave.

    Look for the U-Streams C Library... handy indeed.

    0 讨论(0)
  • 2020-12-18 08:07

    Once it's gone out, it's gone. If you want to compile it all into a single executable, you'll have to go through the code for A with a search and replace and change all those printf calls into ones to your own stream, where you can copy them and then pass them on to stdout.

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