File
Pointers
Accessing
a stream in a C program is done through a file pointer, which has
type
FILE * (the FILE type is declared in). Certain streams are
represented by file pointers with standard names; we can declare additional
tile pointers as needed. For example, if a program needs two streams in
addition to the standard ones, it might contain the following declaration:
FILE * (the FILE type is declared in
FILE *fpl, *fp2;
A
program may declare any number of FILE * variables, although operating systems
usually limit the number of streams that can be open at one time.
Standard
Streams and Redirection
File Pointer
|
Stream
|
Default Meaning
|
stdin
stdout
stderr
|
Standard input
Standard output
Standard error
|
Keyboard
Screen
Screen
|
The
functions that we've used in previous chapters printf, scanf, putchar. getchar.
puts, and gets obtain input from stdin and send output to stdout. By default,
stdin represents the keyboard; stdout and stderr represent the screen. However,
many operating systems allow these default meanings to be changed via a
mechanism known as redirection.
Typically,
we can force a program to obtain its input from a file instead of from the
keyboard by putting the name of the file on the command line, preceded by the
< character:
This technique, known as input redirection.
essentially makes the stdin stream represent a file (in. dat. in this case)
instead of the keyboard. The beauty of redirection is that the demo program
doesn't realize that it's reading from in. dat; as far as it knows, any data it
obtains from stdin is being entered at the keyboard.
Output
redirection is similar. Redirecting the stdout
stream is usually done by putting a file name on the command line, preceded by
the > character:
demo >out.dat
All data written to stdout will now
go into the out. dat file instead of appear-
ing on the
screen. Incidentally, we can combine output redirection with input redirection:
One problem with output redirection is that everything
written to stdout is put into a file. If the program goes off the rails and
begins writing error messages, we won't see them until we look at the file.
This is where stderr comes in. By writing error messages to stderr instead of
stdout, we can guarantee that those messages will appear on the screen even
when stdout has been redirected. (Operating systems often allow stderr itself
to be redirected, though.)
No comments:
Post a Comment