I want to reopen the stdin
and stdout
(and perhaps stderr
while I'm at it) filehandles, so that future calls to printf()
or putchar()
or puts()
will go to a file, and future calls to getc()
and such will come from a file.
1) I don't want to permanently lose standard input/output/error. I may want to reuse them later in the program.
2) I don't want to open new filehandles because these filehandles would have to be either passed around a lot or global (shudder).
3) I don't want to use any open()
or fork()
or other system-dependent functions if I can't help it.
So basically, does it work to do this:
stdin = fopen("newin", "r");
And, if it does, how can I get the original value of stdin
back? Do I have to store it in a FILE *
and just get it back later?
Understanding the concept of redirections and file descriptors is very important when working on the command line. To redirect stderr and stdout , use the 2>&1 or &> constructs.
Input/Output (I/O) redirection in Linux refers to the ability of the Linux operating system that allows us to change the standard input ( stdin ) and standard output ( stdout ) when executing a command on the terminal. By default, the standard input device is your keyboard and the standard output device is your screen.
you can just fclose(stdin), it will call close() on the file handle.
In computer programming, standard streams are interconnected input and output communication channels between a computer program and its environment when it begins execution. The three input/output (I/O) connections are called standard input (stdin), standard output (stdout) and standard error (stderr).
Why use freopen()
? The C89 specification has the answer in one of the endnotes for the section on <stdio.h>
:
116. The primary use of the
freopen
function is to change the file associated with a standard text stream (stderr
,stdin
, orstdout
), as those identifiers need not be modifiable lvalues to which the value returned by thefopen
function may be assigned.
freopen
is commonly misused, e.g. stdin = freopen("newin", "r", stdin);
. This is no more portable than fclose(stdin); stdin = fopen("newin", "r");
. Both expressions attempt to assign to stdin
, which is not guaranteed to be assignable.
The right way to use freopen
is to omit the assignment: freopen("newin", "r", stdin);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With