Sams Teach Yourself C in 21 Days

(singke) #1
Character Input and Output ..........................................................................

When used with disk files, the term character I/Orefers to single characters as well as
lines of characters. Remember, a line is a sequence of zero or more characters terminated
by the newline character. Use character I/O with text-mode files. The following sections
describe character input/output functions, and then you’ll see a demonstration program.

Character Input
There are three character input functions for reading from files:getc(), andfgetc()for
single characters, and fgets()for lines.

Thegetc()andfgetc()Functions The functions getc()andfgetc()are identical
and can be used interchangeably. They input a single character from the specified stream.
Here is the prototype of getc(), which is in stdio.h:
int getc(FILE *fp);
The argument fpis the pointer returned by fopen()when the file was opened. The func-
tion returns the character that was input or EOFon error.
You’ve seen getc()used in earlier programs to input a character from the keyboard. This
is another example of the flexibility of C’s streams—the same function can be used for
keyboard or file input.
Ifgetc()andfgetc()return a single character, why are they prototyped to return a type
int? The reason is that, when reading files, you need to be able to read in the end-of-file
marker, which on some systems isn’t a type charbut a type int. You’ll see getc()in
action later, in Listing 16.10.

450 Day 16

Thegetchar()function is also used to read characters. It, however, reads
Note from the stdinstream rather than from a file you specify.

Thefgets()Function To read a line of characters from a file, use the fgets()
library function. The prototype is
char *fgets(char *str, int n, FILE *fp);
The argument stris a pointer to a buffer in which the input is to be stored. nis the max-
imum number of characters to be input. fpis the pointer to type FILEthat was returned
byfopen()when the file was opened.
When called,fgets()reads characters from fpinto memory, starting at the location
pointed to by str. Characters are read until a newline is encountered or until n-1charac-
ters have been read, whichever occurs first. By setting nequal to the number of bytes

26 448201x-CH16 8/13/02 11:13 AM Page 450

Free download pdf