On 10/29/2012 08:54 AM, sinbad wrote:
> how to redirect stdout to a user specified file.
> and how do i redirect back from the user file to
> stdout.
Just copy the standard output fd first using dup().
Eg.:
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
int main(int argc, char **argv) {
const int old_stdout = dup(1);
FILE *fp = fopen("/tmp/stdout.out", "wb");
printf("Hello, this is printed on standard output\n");
if (fp != NULL) {
const int fp_fd = fileno(fp);
if (dup2(fp_fd, 1) == -1) {
perror("dup2");
}
printf("Hello, this is printed on a file\n");
if (dup2(old_stdout, 1) == -1) {
perror("dup2");
}
printf("Hello, this is printed on standard output again\n");
}
return 0;
}