If you do not have the right to change the source code that prints, you can use freopen
in stdout
to redirect to the file:
stdout = freopen("my_log.txt", "w", stdout);
This limits hacks, as redirects from the command line will stop working as expected. If you have access to code that prints, it is preferable to use fprintf
.
You can also temporarily switch your stdout
to a function call, and then return it:
FILE *saved = stdout; stdout = fopen("log.txt", "a"); call_function_that_prints_to_stdout(); fclose(stdout); stdout = saved;
source share