Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How could I temporary redirect stdout to a file in a C program?

Tags:

c

redirect

stdout

Within my C program, I’d like to temporarly redirect stdout to /dev/null (for example). Then, after writing to /dev/null, I’d like to restore stdout. How do I manage this?

like image 352
Frank Avatar asked Jan 28 '11 20:01

Frank


People also ask

How do you redirect stdout to the file?

Redirecting stdout and stderr to a file: The I/O streams can be redirected by putting the n> operator in use, where n is the file descriptor number. For redirecting stdout, we use “1>” and for stderr, “2>” is added as an operator.

How do I redirect error to stdout?

The regular output is sent to Standard Out (STDOUT) and the error messages are sent to Standard Error (STDERR). When you redirect console output using the > symbol, you are only redirecting STDOUT. In order to redirect STDERR, you have to specify 2> for the redirection symbol.


1 Answers

On POSIX systems, you can do it as follows:

int bak, new;  fflush(stdout); bak = dup(1); new = open("/dev/null", O_WRONLY); dup2(new, 1); close(new);  /* your code here ... */  fflush(stdout); dup2(bak, 1); close(bak); 

What you want is not possible in further generality.

Any solution using freopen is wrong, as it does not allow you to restore the original stdout. Any solution by assignment to stdout is wrong, as stdout is not an lvalue (it's a macro that expands to an expression of type FILE *).

like image 191
R.. GitHub STOP HELPING ICE Avatar answered Sep 20 '22 23:09

R.. GitHub STOP HELPING ICE