Part 4 - Output
---------------
Streams. What an interesting word to hear in a programming language.
I'm going to tell you a little bit about what streams are all about.
Once you understand them, you might find that C's input/output functions
aren't as wierd as they appear.
A stream is a string of data. String might be the wrong word. Perhaps
sequence? Yes. A stream is a sequence of data. When you have to give
a program input, that is an input stream. The input stream in C is
called "stdin". When the program spits data out, either onto disk,
display device or anywhere really, that is called the output stream.
The output stream in C is called "stdout".
That is really all you need to know about streams (at least for now).
There are 3 streams in the C language:
stdin, stdout and stderr. Your operating system or compiler may have
other streams available for your use, such as for printer or COM port
access. These however, will not be discussed.
We will now take a fairly short walkthrough of different ways to
display output. We have already seen uses of the printf statement.
Let's now discuss the fprintf function.
fprintf is almost the same as printf except for one small detail. The
printf function sends output to stdout whereas fprintf specifies the
output stream. Here's a comparison of the two:
printf("Hello World\n");
fprintf(stdout, "Hello World\n");
To use fprintf, you simply need to tell it which stream to use.
Simple no? The fprintf family of functions can produce some overhead
in your programs if you are not using them to thier full potential. If
you really only want to output a string to the output device, feel free
to use the "puts" or "fputs" functions.
puts("Hello World!"); /* the \n is not needed */
fputs("Hello World!\n", stdout); /* The \n IS needed with fputs. */
This will save a small (almost not worth mentioning) amount of disk
space and memory. You can include escape sequences but not
conversion specifiers.
The last two output functions we will discuss are the "fputc" and
"putchar" functions.
They both do relatively the same thing. They place a character into
the output stream. Here's an example:
putchar('A'); /* Display the letter A */
fputc('A', stdout); /* see above comment */
The difference is that "fputc" can direct the output to a different
stream. The only difference between "putc" and "fputc" is that "putc"
may be implemented as a Macro. We might discuss macros at a later
time.
Let's go to Part 5.