Advanced Programming in the UNIX® Environment

(lily) #1
ptg10805159

150 StandardI/O Library Chapter 5


any other operation on the stream, we can change the buffering if we want to, with the
setbuforsetvbuffunctions from the previous section.
An open stream is closed by callingfclose.
#include <stdio.h>
int fclose(FILE *fp);
Returns: 0 if OK,EOFon error
Any buffered output data is flushed beforethe file is closed. Any input data that may
be buffered is discarded. If the standardI/O library had automatically allocated a
buffer for the stream, that buffer is released.
When a process terminates normally,either by calling theexitfunction directly or
by returning from themainfunction, all standardI/O streams with unwritten buffered
data areflushed and all open standardI/O streams areclosed.

5.6 Reading and Writing a Stream


Once we open a stream, we can choose from among three types of unformatted I/O:


  1. Character-at-a-time I/O.We can read or write one character at a time, with the
    standardI/O functions handling all the buffering, if the stream is buffered.

  2. Line-at-a-time I/O. If we want to read or write a line at a time, we usefgets
    andfputs.Each line is terminated with a newline character,and we have to
    specify the maximum line length that we can handle when we callfgets.We
    describe these two functions in Section 5.7.

  3. Direct I/O. This type of I/O is supported by thefreadandfwritefunctions.
    For each I/O operation, we read or write some number of objects, whereeach
    object is of a specified size. These two functions areoften used for binary files
    where we read or write a structurewith each operation. We describe these two
    functions in Section 5.9.
    The termdirect I/O,fromthe ISO C standard, is known by many names: binary I/O,
    object-at-a-time I/O, record-oriented I/O, or structure-oriented I/O. Don’t confuse
    this featurewith theO_DIRECT openflag supported by FreeBSD and Linux—they
    areunrelated.
    (Wedescribe the formatted I/O functions, such asprintfandscanf, in Section 5.11.)


Input Functions


Three functions allow us to read one character at a time.
#include <stdio.h>
int getc(FILE *fp);
int fgetc(FILE *fp);
int getchar(void);
All three return: next character if OK,EOFon end of file or error
Free download pdf