Section 8.2 - Buffered and Unbuffered getchar

Question

Demonstrate buffered and unbuffered getchar using the system read function.

/* Example of an unbuffered and buffered getchar */

#include <stdio.h>
#include <sys/syscall.h>
#include <unistd.h>

#define BUFSIZ 1024

/* unbuffered getchar implementation using read */

int ugetchar(void);

/* buffered getchar implementation using read */
int bgetchar(void);

int main() {
    char c;
    while ((c = ugetchar()) != 'x') {
        putchar(c);
    }

    while ((c = bgetchar()) != 'x') {
        putchar(c);
    }

    return 0;
}

int ugetchar(void) {
    char c;

    return (read(0, &c, 1) == 1) ? (unsigned char) c : EOF;
}

int bgetchar(void) {
    static char buf[BUFSIZ];
    static char *bufp = buf;
    static int n = 0;

    if (n == 0) /* buffer is empty */
    {
        n = read(0, buf, sizeof buf);
        bufp = buf;
    }

    return (--n >= 0) ? (unsigned char) *bufp++ : EOF;
}

Explanation

The un-buffered getchar, uses the system read and stores each character that is read in a character, c and returns the character return (read(0, &c, 1) == 1) ? (unsigned char) c : EOF;

The buffered version of getchar, sets aside a buffer for reading the characters.

static char buf[BUFSIZ];
static char *bufp = buf;

And reads each of the characters into the buffer, read(0, buf, sizeof buf) and then returns one character at a time from the buffer.

The later would be more efficient than the former one.

To execute this program, give the input in the following manner.

stdin
this is buffered getchar x
this is unbuffered getchar x

stdout

this is buffered getchar
this is unbuffered getchar