Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rerouting stdin and stdout from C

Tags:

c

redirect

stdio

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?

like image 372
Chris Lutz Avatar asked Feb 25 '09 05:02

Chris Lutz


People also ask

How do I redirect stdin and stdout?

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.

Can you redirect stdin?

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.

Can you Fclose stdin?

you can just fclose(stdin), it will call close() on the file handle.

What is stdin stdout stderr in C?

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).


1 Answers

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, or stdout), as those identifiers need not be modifiable lvalues to which the value returned by the fopen 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);

like image 177
bk1e Avatar answered Sep 28 '22 00:09

bk1e