←to practical programming
Note "streams"
Streams
The C language uses streams—sequences
of bytes—for all file operations.
The operating system connects these streams with physical devices such
as keyborads, terminals, files and others. Streams in the C language
are objects of the type
FILE*
(pointer to file).
Standard streams
For a C-program three standard streams are always
available: two output streams, the standard output stream,
stdout
, and the standard error stream,
stderr
; and one input stream, the standard input
stream stdin
.
By default the standard output and standard error streams are connected
to the terminal from which the program is run, while the standard input
stream is connected to the terminal's keyboard. (However, these streams
can be easily redirected by the operating system to other desinations.)
File streams
The standard streams are often enough for a program to move its data
around (using redirections). However sometimes you need to write/read
specifically to/from a file with a certain name. You do this by creating
streams explicitly connected with the given files, for example,
FILE* my_in_stream = fopen("input.txt","r");
FILE* my_out_stream = fopen("out.txt","w");
where "r" means "reading" and "w" means "writing" (read
man fopen
for details and other modes of stream operations).
When you are done with your file operations, you should not forget to
close your file streams,
fclose(my_in_stream);
fclose(my_out_stream);
otherwise bad things might happen.
Output
You can send your data to stdout
stream with the
printf
function,
printf("x=%g\n",x);
You can send your data to all other streams
with the fprintf
function,
fprintf(stdout,"x=%g\n",x); // to stdout, same as printf
fprintf(stderr,"x=%g\n",x); // to stderr
fprintf(my_out_stream,"x=%g\n",x); // to my_out_stream
Input
You can input data into your C-program by
- reading from standard input stream,
stdin
;
- reading from file streams;
- reading command-line arguments.
You can read from the streams using either the scanf
function, which reads from stdin, or the fscanf
function
which reads from the specified stream, for example,
int items;
double x;
items = scanf("%g",&x); // from stdin into "x"
items = fscanf(stdin,"%g",&x); // also from stdin
items = fscanf(my_in_stream,"%g",&x); // from my_in_stream