Lab 1 Notes: Standard I/O Library

These notes are based on Chap. 5 of "Advanced Programming in the UNIX Environment" by W. Richard Stevens. These notes are only a quick summary, and are not intended to replace what is written in the book.

Contents:

5.1) Intro
5.2) Streams and FILE Objects
5.3) Standard Input, Standard Output, and Standard Error
5.4) Buffering
5.5) Opening a Stream
5.6) Reading and Writing a Stream
5.7) Line-at-a-Time I/O
5.8) Standard I/O Efficiency
5.9) Binary I/O
5.10) Positioning a Stream
5.11) Formatted I/O
5.12) Implementation Details
5.13) Temporary Files
Appendix: Examples


5.1) Introduction

There are 2 key was to do I/O:
  1. Using file descriptors
  2. Using file streams (as defined by standard I/O library). This is the topic of these notes.

5.2) Streams and FILE Objects

5.3) Standard Input, Standard Output, and Standard Error

5.4) Buffering


5.5) Opening a Stream

5.6) Reading and Writing a Stream

5.7) Line-at-a-Time I/O

5.8) Standard I/O Efficiency

5.9) Binary I/O

5.10) Positioning a Stream

5.11) Formatted I/O

    #include <stdio.h>

    int printf (const char *format, ...);
    /* 
     * printf writes to the standard output. 
     *
     * Returns: the number of characters output if OK, 
     *          negative value if output error
     */
  
    int fprintf (FILE *fp, const char *format, ...);
    /*
     * fprintf writes to the specified stream.
     * 
     * Returns: the number of characters output if OK, 
     *          negative value if output error
     */

    int sprintf (char *buf, const char *format, ...);
    /* 
     * sprintf writes to the character array buf.
     * sprintf automatically appends a null byte at the end of
     * the array, but this null byte is no included in the
     * return value.
     *
     * Returns: the number of characters stored in the array
     */

5.12) Implementation Details

5.13) Temporary Files

Appendix: Examples

  1. Program using setvbuf (contrasting line-buffering against no-buffering)
  2. Program using freopen (redirecting stdout to a file)
  3. Program using fscanf and feof (checking for duplicate words in a file)