Advanced Programming in the UNIX® Environment

(lily) #1
ptg10805159

Section 5.6 Reading and Writing a Stream 151


The functiongetcharis defined to be equivalent togetc(stdin).The difference
betweengetcandfgetcis thatgetccan be implemented as a macro, whereasfgetc
cannot be implemented as a macro. This means three things.


  1. The argument togetcshould not be an expression with side effects, because it
    could be evaluated morethan once.

  2. Sincefgetcis guaranteed to be a function, we can take its address. This allows
    us to pass the address offgetcas an argument to another function.

  3. Calls tofgetcprobably take longer than calls togetc, as it usually takes more
    time to call a function.


These three functions return the next character as anunsigned charconverted to
anint.The reason for specifying unsigned is so that the high-order bit, if set, doesn’t
cause the return value to be negative. The reason for requiring an integer return value
is so that all possible character values can be returned, along with an indication that
either an error occurred or the end of file has been encountered. The constantEOFin
<stdio.h>is required to be a negative value. Its value is often−1. Thisrepresentation
also means that we cannot storethe return value from these three functions in a
character variable and later comparethis value with the constantEOF.
Note that these functions return the same value whether an error occurs or the end
of file is reached. Todistinguish between the two, we must call eitherferrororfeof.
#include <stdio.h>
int ferror(FILE *fp);
int feof(FILE *fp);
Both return: nonzero(true) if condition is true, 0 (false) otherwise
void clearerr(FILE *fp);

In most implementations, two flags aremaintained for each stream in theFILEobject:
•Anerror flag
•Anend-of-file flag
Both flags arecleared by callingclearerr.
After reading from a stream, we can push back characters by callingungetc.
#include <stdio.h>

int ungetc(intc,FILE *fp);
Returns:cif OK,EOFon error

The characters that arepushed back arereturned by subsequent reads on the stream in
reverse order of their pushing. Be aware, however,that although ISO C allows an
implementation to support any amount of pushback, an implementation is required to
provide only a single character of pushback.We should not count on morethan a single
character.
Free download pdf