You might want to use freopen(3) on stdout
but it would close stdout
.
You could use dup2(2) like:
int newfd = open("/tmp/someoutput.txt", O_WRONLY|O_CREAT, 0640);
if (newfd<0) {
perror("/tmp/someoutput.txt"); exit(EXIT_FAILURE); };
if (dup2(STDOUT_FILENO, newfd)) {
perror("dup2"); exit(EXIT_FAILURE); }
But as commented by David Heffernan you really want to use redirections in your shell.
IMHO redirecting STDOUT_FILENO
like above smells bad.
A possible way might be to declare a global
FILE* myout = stdout;
and use always fprintf(myout,
instead of printf(
and perhaps sometimes doing myout = fopen("/tmp/someoutput.txt");
with a test!
At least inform the user that you are redirecting his stdout
(perhaps by some message to stderr
etc...) !