ZetCode

File I/O in K&R C

last modified December 5, 2026 K&R C 1978

The programs so far have read the standard input and written the standard output, and left it to the shell to connect them to files. The standard I/O library can also open files by name. A program then reads and writes them with the same kind of functions it uses for the terminal. The examples in this article use fixed file names; the command-line arguments article shows how to take the names from the command line.

Opening a file

fopen takes a file name and a mode, and returns a file pointer: a pointer to a structure of type FILE, defined in <stdio.h>, that holds the buffer and the state of the open file. The program never looks inside it; it passes the pointer to the other functions.

show.c
#include <stdio.h>

int main()
{
    FILE *fp;
    int c;

    fp = fopen("poem.txt", "r");
    while ((c = getc(fp)) != EOF)
        putchar(c);
    fclose(fp);
    return 0;
}

The mode "r" opens the file for reading. getc(fp) returns the next character of the file, or EOF at its end, exactly like getchar does for the standard input. fclose releases the file when the program is done with it. The file is the poem used in the character input article.

$ gcc -std=c89 -pedantic -Wall -Wextra -o show show.c
$ ./show
The tide comes in without a sound,
it fills the harbour stone by stone,
and every boat that lay aground
is lifted up and rides alone.

The gulls go quiet one by one,
the lamps are lit along the quay;
the tide goes out when night is done
and takes the boats back out to sea.

When a file cannot be opened

fopen returns NULL when it cannot open the file, for example because the file does not exist or may not be read. NULL is the null pointer 0, defined in <stdio.h>. Using a null file pointer crashes the program, so every call must be checked.

opencheck.c
#include <stdio.h>
#include <stdlib.h>

#define NFILES 2

char *names[NFILES] = { "poem.txt", "missing.txt" };

int main()
{
    FILE *fp;
    int i, c, n;

    for (i = 0; i < NFILES; i++) {
        fp = fopen(names[i], "r");
        if (fp == NULL) {
            fprintf(stderr, "cannot open %s\n", names[i]);
            exit(1);
        }
        n = 0;
        while ((c = getc(fp)) != EOF)
            if (c == '\n')
                n++;
        fclose(fp);
        printf("%s: %d lines\n", names[i], n);
    }
    return 0;
}

The program counts the lines of two files. The second one does not exist, so the program prints a message on the standard error and ends with exit(1). exit ends the program from any function, not only from main, and closes the open files first. Its argument is the exit status: 0 means success, and any other value reports a failure to the shell or the program that started this one. exit is declared in <stdlib.h>.

$ gcc -std=c89 -pedantic -Wall -Wextra -o opencheck opencheck.c
$ ./opencheck
poem.txt: 9 lines
cannot open missing.txt
$ echo $?
1

Writing and appending

The mode "w" creates a file for writing, or empties an existing one. The mode "a" appends to the end of a file and creates it if it does not exist. putc(c, fp) writes one character, and fprintf and fputs write formatted text and strings.

table.c
#include <stdio.h>

int show(name)
char *name;
{
    FILE *fp;
    int c;

    if ((fp = fopen(name, "r")) == NULL)
        return 1;
    while ((c = getc(fp)) != EOF)
        putchar(c);
    fclose(fp);
    return 0;
}

int main()
{
    FILE *fp;
    int i;

    fp = fopen("table.txt", "w");
    for (i = 1; i <= 3; i++)
        fprintf(fp, "%d %4d %6d\n", i, i * i, i * i * i);
    fclose(fp);
    show("table.txt");

    printf("-- appended:\n");
    fp = fopen("table.txt", "a");
    fprintf(fp, "%d %4d %6d\n", 10, 100, 1000);
    fclose(fp);
    show("table.txt");

    printf("-- rewritten:\n");
    fp = fopen("table.txt", "w");
    fputs("empty\n", fp);
    fclose(fp);
    show("table.txt");
    return 0;
}

The program writes a small table, appends a row to it, and then opens it with "w" again, which throws the old content away. show prints the file after each step; it reports a missing file with its return value. Output to a file is buffered, and fclose writes the rest of the buffer, so the file must be closed, or flushed, before it is read again.

$ gcc -std=c89 -pedantic -Wall -Wextra -o table table.c
$ ./table
1    1      1
2    4      8
3    9     27
-- appended:
1    1      1
2    4      8
3    9     27
10  100   1000
-- rewritten:
empty

The standard streams

When a program starts, three files are already open: the standard input, the standard output, and the standard error, with the file pointers stdin, stdout, and stderr. getchar() is the same as getc(stdin), and putchar(c) the same as putc(c, stdout).

concat.c
#include <stdio.h>

/* copy file ifp to file ofp */
int file_copy(ifp, ofp)
FILE *ifp, *ofp;
{
    int c;

    while ((c = getc(ifp)) != EOF)
        putc(c, ofp);
    return 0;
}

int main()
{
    FILE *fp;

    if ((fp = fopen("poem.txt", "r")) == NULL) {
        fprintf(stderr, "concat: cannot open poem.txt\n");
        return 1;
    }
    file_copy(fp, stdout);
    fclose(fp);
    file_copy(stdin, stdout);
    return 0;
}

file_copy copies any file to any other, because it receives both as file pointers. The program copies the poem, then its standard input, to the standard output, like the cat command does with its arguments. The standard streams must not be closed with fclose while the program still uses them.

$ gcc -std=c89 -pedantic -Wall -Wextra -o concat concat.c
$ echo '-- the end --' | ./concat
The tide comes in without a sound,
it fills the harbour stone by stone,
and every boat that lay aground
is lifted up and rides alone.

The gulls go quiet one by one,
the lamps are lit along the quay;
the tide goes out when night is done
and takes the boats back out to sea.
-- the end --

Reading lines

fgets(line, max, fp) reads the next line of a file into a character array, including its newline, and adds a null character. It reads at most max - 1 characters, so it never writes past the end of the array. At the end of the file it returns NULL. fputs(line, fp) writes a string to a file.

numlines.c
#include <stdio.h>

#define MAXLINE 100

int main()
{
    FILE *fp;
    char line[MAXLINE];
    int n;

    if ((fp = fopen("poem.txt", "r")) == NULL) {
        fprintf(stderr, "numlines: cannot open poem.txt\n");
        return 1;
    }
    n = 0;
    while (fgets(line, MAXLINE, fp) != NULL) {
        printf("%2d  ", ++n);
        fputs(line, stdout);
    }
    fclose(fp);
    return 0;
}

The program numbers the lines of the poem. fputs adds no newline of its own; the newline that ends each line comes from the line that fgets has read.

$ gcc -std=c89 -pedantic -Wall -Wextra -o numlines numlines.c
$ ./numlines
 1  The tide comes in without a sound,
 2  it fills the harbour stone by stone,
 3  and every boat that lay aground
 4  is lifted up and rides alone.
 5  
 6  The gulls go quiet one by one,
 7  the lamps are lit along the quay;
 8  the tide goes out when night is done
 9  and takes the boats back out to sea.

Long lines

A line that does not fit in the array is not lost. fgets returns as much of it as fits, and the next call continues with the rest. Only the last piece of the line ends with a newline.

pieces.c
#include <stdio.h>

#define MAXLINE 16

/* index of the last character of s */
int last(s)
char s[];
{
    int i;

    for (i = 0; s[i] != '\0'; i++)
        ;
    return i - 1;
}

int main()
{
    FILE *fp;
    char buf[MAXLINE];
    int pieces, lines;

    if ((fp = fopen("poem.txt", "r")) == NULL) {
        fprintf(stderr, "pieces: cannot open poem.txt\n");
        return 1;
    }
    pieces = lines = 0;
    while (fgets(buf, MAXLINE, fp) != NULL) {
        if (lines == 0)
            printf("[%s]\n", buf);
        pieces++;
        if (buf[last(buf)] == '\n')
            lines++;
    }
    fclose(fp);
    printf("%d pieces, %d lines\n", pieces, lines);
    return 0;
}

With an array of 16 characters, each call returns at most 15. The first line of the poem comes in three pieces, printed between brackets; the third piece holds the newline, which moves the closing bracket to the next line. A program counts lines by their newlines, not by the calls of fgets.

$ gcc -std=c89 -pedantic -Wall -Wextra -o pieces pieces.c
$ ./pieces
[The tide comes ]
[in without a so]
[und,
]
24 pieces, 9 lines

End of file and errors

getc returns EOF both at the end of a file and when reading fails. The functions feof(fp) and ferror(fp) tell the two cases apart: one of them returns a non-zero value after the EOF.

readerr.c
#include <stdio.h>

int count(name)
char *name;
{
    FILE *fp;
    long n;

    if ((fp = fopen(name, "r")) == NULL) {
        fprintf(stderr, "cannot open %s\n", name);
        return 1;
    }
    n = 0;
    while (getc(fp) != EOF)
        n++;
    printf("%-9s %5ld bytes, feof %d, ferror %d\n",
        name, n, feof(fp) != 0, ferror(fp) != 0);
    fclose(fp);
    return 0;
}

int main()
{
    count("poem.txt");
    count(".");
    return 0;
}

The program reads a text file and the current directory, ., which fopen opens without complaint on Linux. The poem is read to its end. Linux does not allow reading a directory as a file, so the first getc on it fails, and ferror reports the error.

$ gcc -std=c89 -pedantic -Wall -Wextra -o readerr readerr.c
$ ./readerr
poem.txt    274 bytes, feof 1, ferror 0
.             0 bytes, feof 0, ferror 1

V7 UNIX allows it. A directory is a file of 16-byte entries, each with an inode number and a name of up to 14 characters, and it reads to its end like any other file. The UNIX interface article decodes these entries.

$ cc readerr.c
$ a.out
poem.txt    274 bytes, feof 1, ferror 0
.           112 bytes, feof 1, ferror 0

Binary data

fwrite(ptr, size, n, fp) writes n objects of size bytes each, taken from the memory at ptr, and returns the number of objects written. fread reads them back in the same way. These two functions, like fseek and the update modes of the next section, come from the standard I/O library of V7 UNIX. The book itself reads and writes files with characters, lines, and formatted text.

squares.c
#include <stdio.h>

#define N 10

int main()
{
    FILE *fp;
    int v[N], w[N];
    int i, n;

    for (i = 0; i < N; i++)
        v[i] = i * i;
    fp = fopen("squares.dat", "w");
    n = fwrite((char *) v, sizeof(int), N, fp);
    printf("wrote %d numbers, %ld bytes\n", n, ftell(fp));
    fclose(fp);

    fp = fopen("squares.dat", "r");
    n = fread((char *) w, sizeof(int), N, fp);
    fclose(fp);
    printf("read %d numbers:", n);
    for (i = 0; i < n; i++)
        printf(" %d", w[i]);
    printf("\n");
    return 0;
}

The array goes to the file as the bytes of its integers, not as text. ftell returns the current position in the file, a long, which after writing is the size of the file. The cast to char * was the usual way to pass any pointer to these functions. UNIX makes no difference between text and binary files, so the mode "r" serves for both; systems that convert line endings in text files need the mode "rb" for binary data.

$ gcc -std=c89 -pedantic -Wall -Wextra -o squares squares.c
$ ./squares
wrote 10 numbers, 40 bytes
read 10 numbers: 0 1 4 9 16 25 36 49 64 81

A binary file depends on the machine that wrote it. On the PDP-11 an int has two bytes, so the same ten numbers take 20 bytes. A file written on one machine cannot be read with fread on the other.

$ cc squares.c
$ a.out
wrote 10 numbers, 20 bytes
read 10 numbers: 0 1 4 9 16 25 36 49 64 81

Random access

fseek(fp, offset, origin) moves the position in a file, so the next read or write happens there. The long offset counts from the beginning of the file when the origin is 0, from the current position when it is 1, and from the end when it is 2. A file of records of one size can be read in any order.

records.c
#include <stdio.h>

#define NREC 4

struct part {
    char p_name[10];
    int p_qty;
} parts[NREC] = {
    { "bolt", 120 }, { "nut", 300 }, { "washer", 75 }, { "spring", 40 }
};

int main()
{
    FILE *fp;
    struct part p;
    int i;

    fp = fopen("parts.dat", "w");
    fwrite((char *) parts, sizeof(struct part), NREC, fp);
    fclose(fp);

    fp = fopen("parts.dat", "r+");
    printf("record size %d\n", (int) sizeof(struct part));
    for (i = NREC - 1; i >= 0; i -= 2) {
        fseek(fp, (long) i * sizeof(struct part), 0);
        printf("record %d at byte %ld: ", i, ftell(fp));
        fread((char *) &p, sizeof(struct part), 1, fp);
        printf("%s %d\n", p.p_name, p.p_qty);
    }

    p.p_qty = 0;
    fseek(fp, -(long) sizeof(struct part), 1);
    fwrite((char *) &p, sizeof(struct part), 1, fp);
    fseek(fp, 0L, 0);
    while (fread((char *) &p, sizeof(struct part), 1, fp) == 1)
        printf("%s=%d ", p.p_name, p.p_qty);
    printf("\n");
    fclose(fp);
    return 0;
}

The program writes four records, then reads records 3 and 1 directly. The mode "r+" opens the file for both reading and writing. After reading record 1, fseek with origin 1 moves back by one record, and the program writes a changed copy over it. A change between reading and writing must always go through fseek. The last loop reads the whole file from the start.

$ gcc -std=c89 -pedantic -Wall -Wextra -o records records.c
$ ./records
record size 16
record 3 at byte 48: spring 40
record 1 at byte 16: nut 300
bolt=120 nut=0 washer=75 spring=40 

The record of ten characters and an int has 16 bytes with GCC, which aligns the int to a multiple of four, and 12 bytes on the PDP-11, so the records begin at other offsets.

$ cc records.c
$ a.out
record size 12
record 3 at byte 36: spring 40
record 1 at byte 12: nut 300
bolt=120 nut=0 washer=75 spring=40 

Source

Dennis Ritchie: C Reference Manual (1975)

Linux manual: fopen, fdopen, freopen

In this article we have worked with files in K&R C: fopen and fclose, checking for NULL and ending with exit, the modes "r", "w", and "a", the standard streams, lines with fgets and fputs, feof and ferror, binary data with fread and fwrite, and random access with fseek and ftell. The next article surveys the standard library. Modern C covers the same functions in fopen, fgets, fread, and fseek.

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.