Sams Teach Yourself C in 21 Days

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

14


What Is a Stream? ........................................................................................

Astreamis a sequence of characters. More exactly, it is a sequence of bytes of
data. A sequence of bytes flowing into a program is an input stream; a sequence
of bytes flowing out of a program is an output stream. By focusing on streams, you don’t
have to worry as much about where they’re going or where they originated. The major
advantage of streams, therefore, is that input/output programming is device independent.
Programmers don’t need to write special input/output functions for each device (key-
board, disk, and so on). The program sees input/output as a continuous stream of bytes
no matter where the input is coming from or going to.
Every C stream is connected to a file. In this context, the term filedoesn’t refer
to a disk file. Rather, it is an intermediate step between the stream that your pro-
gram deals with and the actual physical device being used for input or output. For the
most part, the beginning C programmer doesn’t need to be concerned with these files,
because the details of interactions between streams, files, and devices are taken care of
automatically by the C library functions and the operating system.

Text Versus Binary Streams ..........................................................................

C streams fall into two modes: text and binary. A text stream consists only of characters,
such as text data being sent to the screen. Text streams are organized into lines, which
can be up to 255 characters long and are terminated by an end-of-line, or newline, char-
acter. Certain characters in a text stream are recognized as having special meaning, such
as the newline character. Today’s lesson deals with text streams.
Abinarystream can handle any sort of data, including, but not limited to, text
data. Bytes of data in a binary stream aren’t translated or interpreted in any spe-
cial way; they are read and written exactly as-is. Binary streams are used primarily with
disk files, which are covered in Day 16, “Using Disk Files.”

Predefined Streams ........................................................................................

The ANSI standard for C has three predefined streams, also referred to as the standard
input/output files. If you’re programming for an IBM-compatible PC running Windows
or DOS, then two additional standard streams may available to you. These streams are
automatically opened when a C program starts executing and are closed when the pro-
gram terminates. The programmer doesn’t need to take any special action to make these
streams available. Table 14.1 lists the standard streams and the devices they normally are
connected with. All five of the standard streams are text-mode streams.

NEWTERM

NEWTERM

NEWTERM

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

Free download pdf