C modifying printf () to output to a file C modifying printf () to output to a file unix unix

C modifying printf () to output to a file


If you do not have liberty to modify the source code that does printing, you can use freopen on stdout to redirect to a file:

stdout = freopen("my_log.txt", "w", stdout);

This borders on a hack, however, because command-line redirects will stop working as expected. If you do have access to the code that does printing, using fprintf is preferred.

You can also switch your stdout temporarily for a function call, and then put it back:

FILE *saved = stdout;stdout = fopen("log.txt", "a");call_function_that_prints_to_stdout();fclose(stdout);stdout = saved;


This is usually done with I/O-redirection (... >file).

Check this little program:

#include <stdio.h>#include <unistd.h>int main (int argc, char *argv[]) {    if (isatty (fileno (stdout)))        fprintf (stderr, "output goes to terminal\n");    else        fprintf (stderr, "output goes to file\n");    return 0;}ottj@NBL3-AEY55:~ $ ./xoutput goes to terminalottj@NBL3-AEY55:~ $ ./x >yyoutput goes to file


The other answers don't cope with the problem of not changing any code.

So, depending on the environment, the only thing that is left is stdout redirection when calling the program.

./program > target_file