Sams Teach Yourself C in 21 Days

(singke) #1
Working with the Screen, Printer, and Keyboard 341

14


All these functions require that you include stdio.h. The function perror()may also
require stdlib.h. The functions vprintf()andvfprintf()also require stdargs.h. On
UNIX systems,vprintf()andvfprintf()may also require varargs.h. Your compiler’s
Library Reference will state whether any additional or alternative header files are needed.

An Example ..................................................................................................

The short program in Listing 14.1 demonstrates the equivalence of streams.

LISTING14.1 stream.c. The equivalence of streams
1: /* Demonstrates the equivalence of stream input and output. */
2: #include <stdio.h>
3:
4: int main( void )
5: {
6: char buffer[256];
7:
8: /* Input a line, then immediately output it. */
9:
10: puts(gets(buffer));
11:
12: return 0;
13: }

On line 10, the gets()function is used to input a line of text from the keyboard (stdin).
Becausegets()returns a pointer to the string, it can be used as the argument to puts(),
which displays the string on-screen (stdout). When run, this program inputs a line of
text from the user and then immediately displays the string on-screen.

DOtake advantage of the standard
input/output streams that C provides.

DON’Trename or change the standard
streams unnecessarily.
DON’Ttry to use an input stream such as
stdinfor an output function such as
fprintf().

DO DON’T


For a beginner learning to program C, using gets()is fine. For a real-world program,
however, you should use fgets()(explained later in today’s lesson) as gets()poses
some risks to program security.

22 448201x-CH14 8/13/02 11:12 AM Page 341

Free download pdf