Add Book to My BookshelfPurchase This Book Online

Chapter 4 - The Standard I/O Library

UNIX Systems Programming for SVR4
David A. Curry
 Copyright © 1996 O'Reilly & Associates, Inc.

Buffer-Based Input and Output
A third I/O paradigm offered by the Standard I/O Library is that of buffer-based I/O, in which buffers full of characters are read and written in large chunks. This method is almost identical to the paradigm offered by the low-level interface described in Chapter 3, except that the library still provides internal buffering services regardless of the size of the buffers used by the program.
There are two functions for performing buffer-based I/O, fread and fwrite:
    #include <stdio.h>
    size_t fread(void *ptr, size_t size, size_t nitems, FILE *stream);
    size_t fwrite(const void *ptr, size_t size, size_t nitems, FILE *stream);
The fread function reads nitems of data, each of size size, from stream, and places them into the array pointed to by ptr. It returns the number of items (not the number of bytes) read, zero if no items were read, or the constant EOF if end-of-file is encountered before any data was read. The fwrite function copies nitems of data, each of size size, from the array pointed to by ptr to the output stream stream. It returns the number of items (not the number of bytes) written, or EOF if an error occurs.
Example 4-3 shows one last version of our file-appending program; this one uses fread and fwrite.
Example 4-3:  append-buf
#include <stdio.h>
int
main(int argc, char **argv)
{
    int n;
    FILE *in, *out;
    char buf[BUFSIZ];
    if (argc != 3) {
        fprintf(stderr, "Usage: append-line file1 file2\n");
        exit(1);
    }
    /*
     * Open the first file for reading.
     */
    if ((in = fopen(argv[1], "r")) == NULL) {
        perror(argv[1]);
        exit(1);
    }
    /*
     * Open the second file for writing.
     */
    if ((out = fopen(argv[2], "a")) == NULL) {
        perror(argv[2]);
        exit(1);
    }
    /*
     * Copy data from the first file to the second, a buffer
     * full at a time.
     */
    while ((n = fread(buf, sizeof(char), BUFSIZ, in)) > 0)
        fwrite(buf, sizeof(char), n, out);
    fclose(out);
    fclose(in);
    exit(0);
}
    % cat a
    file a line one
    file a line two
    file a line three
    % cat b
    file b line one
    file b line two
    file b line three
    % append-buf a b
    % cat b
    file b line one
    file b line two
    file b line three
    file a line one
    file a line two
    file a line three

Previous SectionNext Section
Books24x7.com, Inc © 2000 –  Feedback