ZetCode

The UNIX interface in K&R C

last modified December 5, 2026 K&R C 1978

The standard I/O library is built on a few system calls, functions that ask the UNIX kernel to do the work. They know nothing of formats, lines, or buffers; they move bytes between a program and a file. C was written to implement UNIX, and a C program calls the kernel as easily as it calls any other function. This article uses the system calls directly. They are not part of the C language, and programs that use them run only on UNIX and its descendants.

File descriptors

The kernel identifies an open file by a small non-negative integer, the file descriptor. A program starts with three open descriptors: 0 for the standard input, 1 for the standard output, and 2 for the standard error. write(fd, buf, n) writes n bytes from buf to the file fd.

fds.c
#include <unistd.h>

int main()
{
    write(1, "Hello there!\n", 13);
    write(2, "a message on the standard error\n", 32);
    write(1, "Bye\n", 4);
    return 0;
}

There is no format and no null character: the program gives the number of bytes itself. <unistd.h> declares the system calls on Linux. Unlike the library functions, write does not buffer anything, so each call reaches the file at once.

$ gcc -std=c89 -pedantic -Wall -Wextra -o fds fds.c
$ ./fds
Hello there!
a message on the standard error
Bye

Reading and writing

read(fd, buf, n) reads up to n bytes into buf and returns the number of bytes read, 0 at the end of the file, and -1 on an error. A read from a terminal returns one line, and a read from a file as much as is left, up to n.

rawcopy.c
#include <stdio.h>
#include <unistd.h>

int main()
{
    char buf[BUFSIZ];
    int n, calls;

    calls = 0;
    while ((n = read(0, buf, BUFSIZ)) > 0) {
        write(1, buf, n);
        calls++;
    }
    fprintf(stderr, "%d calls of read, BUFSIZ %d\n", calls + 1, BUFSIZ);
    return 0;
}

The program copies its input to its output in blocks of BUFSIZ bytes, the buffer size that <stdio.h> defines for the standard I/O library. The message on the standard error counts the calls, including the last one, which returns 0. The input is the system's word list, and the copy goes to a file.

$ gcc -std=c89 -pedantic -Wall -Wextra -o rawcopy rawcopy.c
$ ./rawcopy < /usr/share/dict/words > copy.txt
122 calls of read, BUFSIZ 8192

On V7, BUFSIZ is 512, the size of a disk block. The word list of V7 is much smaller, but it takes three times as many calls.

$ cc rawcopy.c
$ a.out < /usr/dict/words > copy.txt
385 calls of read, BUFSIZ 512

A buffered getchar

Every system call costs a switch into the kernel and back. Reading one character per call is simple, but slow; the standard I/O library reads a whole buffer at once and hands out the characters one by one. The next program builds both versions of a character reader on read.

getch.c
#include <stdio.h>
#include <fcntl.h>
#include <unistd.h>

int reads;      /* number of read calls */

/* unbuffered: one read per character */
int raw_get(fd)
int fd;
{
    char c;

    reads++;
    return read(fd, &c, 1) == 1 ? c & 0377 : EOF;
}

/* buffered: one read per bufferful */
int buf_get(fd)
int fd;
{
    static char buf[BUFSIZ];
    static char *bufp;
    static int n = 0;

    if (n == 0) {
        reads++;
        n = read(fd, buf, BUFSIZ);
        bufp = buf;
    }
    return --n >= 0 ? *bufp++ & 0377 : EOF;
}

int main()
{
    int fd;
    long chars;

    fd = open("poem.txt", 0);
    chars = reads = 0;
    while (raw_get(fd) != EOF)
        chars++;
    printf("unbuffered: %ld characters, %d reads\n", chars, reads);
    close(fd);

    fd = open("poem.txt", 0);
    chars = reads = 0;
    while (buf_get(fd) != EOF)
        chars++;
    printf("buffered: %ld characters, %d reads\n", chars, reads);
    close(fd);
    return 0;
}

raw_get reads one byte per call. buf_get keeps a static buffer, a pointer to the next character, and the number of characters left, and calls read only when the buffer is empty. The & 0377 turns a byte with the high bit set into a positive value, so that it cannot be taken for EOF. The names differ in their first letters on purpose: V7 keeps only the first seven characters of an external name, so get_char1 and get_char2 would be the same function there.

$ gcc -std=c89 -pedantic -Wall -Wextra -o getch getch.c
$ ./getch
unbuffered: 274 characters, 275 reads
buffered: 274 characters, 2 reads

Opening, creating, and closing

open(name, mode) opens an existing file and returns a file descriptor, or -1 on failure. The mode is 0 for reading, 1 for writing, and 2 for both. creat(name, perms) creates a new file, or empties an existing one, and opens it for writing. The permissions are the nine UNIX permission bits, written in octal. close releases a descriptor.

fcopy.c
#include <stdio.h>
#include <stdlib.h>
#include <fcntl.h>
#include <unistd.h>

#define PERMS 0644      /* rw for owner, r for group and others */

int error(msg, name)
char *msg, *name;
{
    fprintf(stderr, "fcopy: %s %s\n", msg, name);
    exit(1);
}

int main()
{
    int f1, f2, n;
    long total;
    char buf[BUFSIZ];

    if ((f1 = open("poem.txt", 0)) == -1)
        error("cannot open", "poem.txt");
    if ((f2 = creat("poem.bak", PERMS)) == -1)
        error("cannot create", "poem.bak");
    total = 0;
    while ((n = read(f1, buf, BUFSIZ)) > 0) {
        if (write(f2, buf, n) != n)
            error("write error on", "poem.bak");
        total += n;
    }
    close(f1);
    close(f2);
    printf("copied %ld bytes\n", total);
    return 0;
}

The program copies the poem to a new file in blocks. error prints a message and ends the program; it is declared int like any function without a useful value. write returns the number of bytes written, and anything less than n is an error, for example a full disk. <fcntl.h> declares open and creat on Linux.

$ gcc -std=c89 -pedantic -Wall -Wextra -o fcopy fcopy.c
$ ./fcopy
copied 274 bytes

System call errors

A failing system call returns -1 and stores an error number in the external variable errno. perror(s) prints the string s and a description of the last error on the standard error.

errors.c
#include <stdio.h>
#include <errno.h>
#include <fcntl.h>
#include <unistd.h>

int try_open(name, mode)
char *name;
int mode;
{
    int fd;

    errno = 0;
    fd = open(name, mode);
    printf("open(\"%s\", %d) = %d, errno %d\n", name, mode, fd, errno);
    if (fd == -1)
        perror(name);
    else
        close(fd);
    return fd;
}

int main()
{
    try_open("poem.txt", 0);
    try_open("missing.txt", 0);
    try_open("/etc/passwd", 1);
    try_open("/", 1);
    return 0;
}

The program sets errno to 0 before each call, because a successful call does not clear it. The numbers are the classic UNIX error codes: 2 for a missing file, 13 for missing permission, and 21 for an attempt to write to a directory. Linux and V7 use the same numbers and messages. On Linux <errno.h> declares errno; a V7 program declares it itself with extern int errno;.

$ gcc -std=c89 -pedantic -Wall -Wextra -o errors errors.c
$ ./errors
open("poem.txt", 0) = 3, errno 0
open("missing.txt", 0) = -1, errno 2
missing.txt: No such file or directory
open("/etc/passwd", 1) = -1, errno 13
/etc/passwd: Permission denied
open("/", 1) = -1, errno 21
/: Is a directory

Random access with lseek

Every open file has a current position, where the next read or write begins. lseek(fd, offset, origin) moves it. The origin is 0, 1, or 2, as with fseek: the offset counts from the start, the current position, or the end. lseek returns the new position as a long.

seek.c
#include <stdio.h>
#include <fcntl.h>
#include <unistd.h>

/* read n bytes at position pos of file fd into buf */
int get_at(fd, pos, buf, n)
int fd;
long pos;
char *buf;
int n;
{
    lseek(fd, pos, 0);
    n = read(fd, buf, n);
    buf[n > 0 ? n : 0] = '\0';
    return n;
}

int main()
{
    int fd;
    long size;
    char buf[20];

    if ((fd = open("poem.txt", 0)) == -1) {
        fprintf(stderr, "seek: cannot open poem.txt\n");
        return 1;
    }
    size = lseek(fd, 0L, 2);
    printf("size %ld\n", size);
    get_at(fd, 4L, buf, 4);
    printf("bytes 4-7: %s\n", buf);
    get_at(fd, size - 5, buf, 3);
    printf("last word: %s\n", buf);
    close(fd);
    return 0;
}

Seeking to offset 0 from the end returns the size of the file. get_at reads a few bytes at any position: the first word after The, and the last word before the final period and newline.

$ gcc -std=c89 -pedantic -Wall -Wextra -o seek seek.c
$ ./seek
size 274
bytes 4-7: tide
last word: sea

Declaring lseek

lseek returns a long, so it must be declared before it is called, like every function that does not return an int. A V7 program declares it itself with long lseek();; on Linux the declaration is in <unistd.h>. The next program has no declaration.

nodecl.c
#include <stdio.h>
#include <fcntl.h>

int main()
{
    int fd;
    long size;

    fd = open("poem.txt", 0);
    size = lseek(fd, 0L, 2);
    printf("size %ld\n", size);
    return 0;
}

The compiler assumes that lseek returns an int and warns about the implicit declaration. On x86-64 the long result is in a 64-bit register, and the assumed int takes its low half, which is correct for a small file.

$ gcc -std=c89 -pedantic -Wall -Wextra -o nodecl nodecl.c
nodecl.c: In function ‘main’:
nodecl.c:10:12: warning: implicit declaration of function ‘lseek’; did you mean ‘fseek’? [-Wimplicit-function-declaration]
   10 |     size = lseek(fd, 0L, 2);
      |            ^~~~~
      |            fseek
$ ./nodecl
size 274

On the PDP-11 a long is returned in two registers, the high word in the one where an int result is expected. The program takes the high word, 0, as the whole result, and V7's cc does not warn.

$ cc nodecl.c
$ a.out
size 0

File information

stat(name, &st) fills a struct stat, defined in <sys/stat.h>, with what the system knows about a file: its type and permissions in st_mode, the number of links, the owner, the size, and the times.

fileinfo.c
#include <stdio.h>
#include <sys/types.h>
#include <sys/stat.h>

#define TYPE_MASK 0170000  /* the file type bits of st_mode */
#define DIR_TYPE  0040000  /* the type of a directory */

int info(name)
char *name;
{
    struct stat st;

    if (stat(name, &st) == -1) {
        fprintf(stderr, "fileinfo: cannot stat %s\n", name);
        return 1;
    }
    printf("%-9s %s, mode %03o, %d link%s, %ld bytes\n", name,
        (st.st_mode & TYPE_MASK) == DIR_TYPE ? "directory" : "file",
        (int) st.st_mode & 0777, (int) st.st_nlink,
        st.st_nlink == 1 ? "" : "s", (long) st.st_size);
    return 0;
}

int main()
{
    info("poem.txt");
    info(".");
    info("/");
    info("missing");
    return 0;
}

The high bits of st_mode hold the file type and the low nine bits the permissions. The two constants are the traditional UNIX values, the same on V7 and on Linux. The number of links of a directory includes the .. entries of its subdirectories. stat needs no open file, and it fails with -1 for a missing one.

$ gcc -std=c89 -pedantic -Wall -Wextra -o fileinfo fileinfo.c
$ ./fileinfo
poem.txt  file, mode 664, 1 link, 274 bytes
.         directory, mode 775, 4 links, 4096 bytes
/         directory, mode 755, 20 links, 4096 bytes
fileinfo: cannot stat missing

Reading a directory on V7

On V7 a directory is a file of 16-byte entries. Each entry is a struct direct, defined in <sys/dir.h>: a two-byte inode number, d_ino, and a name, d_name, of DIRSIZ, 14, characters. A program lists a directory by opening it and reading the entries with read, as the book does.

lsdir.c
#include <stdio.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <sys/dir.h>

int main()
{
    int fd, i;
    struct direct d;
    struct stat st;
    char name[DIRSIZ + 1];

    if ((fd = open(".", 0)) == -1) {
        fprintf(stderr, "lsdir: cannot open .\n");
        return 1;
    }
    while (read(fd, (char *) &d, sizeof d) == sizeof d) {
        if (d.d_ino == 0)       /* unused entry */
            continue;
        for (i = 0; i < DIRSIZ; i++)
            name[i] = d.d_name[i];
        name[DIRSIZ] = '\0';
        if (stat(name, &st) == -1)
            continue;
        printf("%5d %-14s %6ld\n", d.d_ino, name, st.st_size);
    }
    close(fd);
    return 0;
}

An entry with the inode number 0 belongs to a removed file and is skipped. A name of 14 characters has no null character at the end, so the program copies the name into a longer array and ends it there. The size comes from stat. This is why file names on V7 have at most 14 characters.

$ cc lsdir.c
$ a.out
 1952 .                 144
  302 ..                208
  128 lsdir.c           684
 1949 a.out            4790

Reading a directory on Linux

Linux file systems store directories in their own formats, and read on a directory fails, as the file I/O article showed. The library functions opendir, readdir, and closedir, declared in <dirent.h>, hide the format. They came to UNIX after V7, and they are the portable way to list a directory.

lsdir.c
#include <stdio.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <dirent.h>

int main()
{
    DIR *dp;
    struct dirent *dep;
    struct stat st;

    if ((dp = opendir(".")) == NULL) {
        fprintf(stderr, "lsdir: cannot open .\n");
        return 1;
    }
    while ((dep = readdir(dp)) != NULL) {
        if (stat(dep->d_name, &st) == -1)
            continue;
        printf("%8ld %-14s %6ld\n", (long) dep->d_ino, dep->d_name,
            (long) st.st_size);
    }
    closedir(dp);
    return 0;
}

readdir returns a pointer to a struct dirent for each entry and NULL at the end. The name is a proper string, and names may be long. The inode numbers are large, and the entries come in the order of the file system, not sorted.

$ gcc -std=c89 -pedantic -Wall -Wextra -o lsdir lsdir.c
$ ./lsdir
 9332156 lsdir.c           516
 9332155 .                4096
 9332181 lsdir           16080
 9332115 ..               4096

Source

Dennis Ritchie: C Reference Manual (1975)

Linux manual: read

In this article we have used the UNIX system calls from K&R C: file descriptors, read and write, a buffered reader built on them, open, creat, and close, errno and perror, lseek and why it must be declared, stat, and directories read as files on V7 and with readdir on Linux. The next article takes the file names from the command line. Modern C covers the library side in fopen and strerror.

Author

I am Jan Bodnar, a programmer and technical writer. I have been writing programming tutorials at ZetCode since 2007 and have published eight e-books. See about the author.

List all K&R C tutorials.