How to capture printf output?

I call the funcB function from funcA . funcB uses several printf statements to output data. Is there a way to capture this data through funcA ? I can not change funcB .

 funcB(){ printf( "%s", "My Name is" ); printf( "%s", "I like ice cream" ); } funcA(){ funcB(); } 
+7
source share
4 answers

(This answer is a revised version based on this answer .)

This answer is POSIX oriented. Use open to create a file descriptor for the file you want to redirect to. Then use dup2 for STDOUT_FILENO to change stdout to write to the file. But, you will want a dup in STDOUT_FILENO before you do this, so that you can restore stdout with another dup2 .

 fflush(stdout); int stdout_fd = dup(STDOUT_FILENO); int redir_fd = open(redirected_filename, O_WRONLY); dup2(redir_fd, STDOUT_FILENO); close(redir_fd); funcB(); fflush(stdout); dup2(stdout_fd, STDOUT_FILENO); close(stdout_fd); 

If funcB uses std::cout , use std::cout.flush() instead of fflush(stdout) .

If you want to control C ++ threads more directly, you can use Jonathan Wakeley's answer .

+11
source

If nothing in your program uses printf , you can write your own version and link it directly. The component will not look in the standard library if the function is already defined. You can use vsprintf for implementation or some more secure version with overflow check if provided by your compiler.

+1
source

If you are ready to play a dirty game located on printf , you can "steal" its output by doing something like:

 #include <stdio.h> #include <stdarg.h> static char buffer[1024]; static char *next = buffer; static void funcB(){ printf( "%s", "My Name is" ); printf( "%s", "I like ice cream" ); } static void funcA(){ funcB(); // Do stuff iwth buffer here fprintf(stderr, "stole: %s\n", buffer); next=buffer; // reset for later. } int main() { funcA(); } int printf(const char *fmt, ...) { va_list argp; va_start(argp, fmt); const int ret = vsnprintf(next, sizeof buffer-(next-buffer), fmt, argp); next += ret; va_end(argp); return ret; } 

You can use the flag to specify how to handle instances in which you want printf to work as usual. (For example, draw it on fprintf or use dlsym() / to find the real call).

You can also use realloc for more intelligent buffer size management.

+1
source

Put funcB in a separate program. Then you can write your standard output, for example. by pipeline or by redirecting it to a file. How to do this, as a rule, depends on the OS and is outside the scope of C ++.

Alternatively, perhaps you can redirect your standard funcA process output to a file, then call funcB and extract the result from the file.

Again, how to do this goes beyond C ++ and depends on the OS.

0
source

All Articles