ZetCode

Text processing in K&R C

last modified December 5, 2026 K&R C 1978

Much of UNIX is made of small programs that read text, change it, and write it out: filters. A filter reads its standard input and writes its standard output, so filters can be joined with pipes. C was written to build such tools, and the book's examples are full of them. This article writes a few, each reading lines with fgets from the file I/O article.

Finding lines

The first program of the book's chapter on functions prints the lines that contain a pattern, a simple version of the UNIX grep. The search for the pattern is a function of its own, which makes the main loop short.

pattern.c
#include <stdio.h>

#define MAXLINE 200

/* the index of t in s, or -1 if s does not contain t */
int strindex(s, t)
char s[], t[];
{
    int i, j, k;

    for (i = 0; s[i] != '\0'; i++) {
        for (j = i, k = 0; t[k] != '\0' && s[j] == t[k]; j++, k++)
            ;
        if (k > 0 && t[k] == '\0')
            return i;
    }
    return -1;
}

/* print the lines that contain the pattern */
int main(argc, argv)
int argc;
char *argv[];
{
    char line[MAXLINE];
    int found;

    if (argc != 2) {
        fprintf(stderr, "usage: pattern text\n");
        return 2;
    }
    found = 0;
    while (fgets(line, MAXLINE, stdin) != NULL)
        if (strindex(line, argv[1]) >= 0) {
            printf("%s", line);
            found++;
        }
    return found > 0 ? 0 : 1;
}

strindex tries each position of s in turn and compares the following characters with t. If the comparison reaches the end of t, the pattern starts at position i. The empty pattern is not found anywhere, because k stays 0. The pattern comes from the command line, and the exit status follows the convention of grep: 0 if a line was found, 1 if none, and 2 for a usage error.

$ gcc -std=c89 -pedantic -Wall -Wextra -o pattern pattern.c
$ ./pattern one < poem.txt
it fills the harbour stone by stone,
is lifted up and rides alone.
The gulls go quiet one by one,
the tide goes out when night is done
$ ./pattern whale < poem.txt
$ echo $?
1

The pattern is a string of characters, not a word: one is found in stone, alone, and done.

Trimming lines

Lines often end with blanks and tabs that nobody can see. A function that removes them, together with the newline, is one of the small examples of the book's chapter on control flow.

trim.c
#include <stdio.h>
#include <string.h>

#define MAXLINE 200

/* remove blanks, tabs, and newlines at the end of s */
int trim(s)
char s[];
{
    int n;

    for (n = strlen(s) - 1; n >= 0; n--)
        if (s[n] != ' ' && s[n] != '\t' && s[n] != '\n')
            break;
    s[n + 1] = '\0';
    return n + 1;
}

int main()
{
    char line[MAXLINE];
    int before, after;

    while (fgets(line, MAXLINE, stdin) != NULL) {
        before = strlen(line);
        after = trim(line);
        printf("%2d -> %2d [%s]\n", before, after, line);
    }
    return 0;
}

trim starts at the last character and moves back while it finds a blank, a tab, or a newline. The break leaves the loop at the first other character, and a '\0' is stored after it. For a line that has nothing else, n ends at -1, and the string becomes empty. The program prints the length before and after and the trimmed line in brackets.

messy.txt
Lines   
  end with blanks	

and tabs.	 	

The first line of the input ends with three blanks, the second with a tab, and the last with a mixture of both; the third line is empty. The blanks at the start of the second line stay.

$ gcc -std=c89 -pedantic -Wall -Wextra -o trim trim.c
$ ./trim < messy.txt
 9 ->  5 [Lines]
19 -> 17 [  end with blanks]
 1 ->  0 []
13 ->  9 [and tabs.]

Sorting lines

To sort lines, a program must hold all of them in memory. Moving whole lines around would be slow, so the book keeps the lines where they were read and sorts an array of pointers to them, as the pointers and arrays article described.

sortlines.c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#define MAXLINES 500            /* lines that can be sorted */
#define MAXLEN   200            /* longest line */

char *lineptr[MAXLINES];        /* pointers to the lines */

/* read the lines into storage from malloc; -1 if there are too many */
int readlines(lineptr, maxlines)
char *lineptr[];
int maxlines;
{
    int nlines;
    char *p, line[MAXLEN];

    nlines = 0;
    while (fgets(line, MAXLEN, stdin) != NULL) {
        if (nlines >= maxlines)
            return -1;
        if ((p = malloc(strlen(line) + 1)) == NULL)
            return -1;
        strcpy(p, line);
        lineptr[nlines++] = p;
    }
    return nlines;
}

int cmpline(a, b)       /* a and b point to elements of lineptr */
char *a, *b;
{
    return strcmp(*(char **) a, *(char **) b);
}

int main()
{
    int nlines, i;

    if ((nlines = readlines(lineptr, MAXLINES)) < 0) {
        fprintf(stderr, "sortlines: input too big to sort\n");
        return 1;
    }
    qsort((char *) lineptr, nlines, sizeof lineptr[0], cmpline);
    for (i = 0; i < nlines; i++)
        printf("%s", lineptr[i]);
    return 0;
}

readlines reads each line into the local array line, gets storage of the right size from malloc, copies the line there, and stores the pointer in lineptr. It returns -1 if there are more lines than pointers or no more memory. The pointers are sorted with qsort from the sorting article. The elements are pointers, so the comparison function receives pointers to pointers: *(char **) a is the line. Only the pointers move; the lines stay where they are.

$ gcc -std=c89 -pedantic -Wall -Wextra -o sortlines sortlines.c
$ ./sortlines < poem.txt

The gulls go quiet one by one,
The tide comes in without a sound,
and every boat that lay aground
and takes the boats back out to sea.
is lifted up and rides alone.
it fills the harbour stone by stone,
the lamps are lit along the quay;
the tide goes out when night is done

The order is the order of the character codes. The empty line comes first, the lines that start with a capital letter follow, and the lines that start with a small letter come last.

Removing repeated lines

Once the lines are sorted, equal lines stand next to each other. A filter that compares each line with the previous one can then drop the repeated lines and count them, like the UNIX uniq -c.

uniq.c
#include <stdio.h>
#include <string.h>

#define MAXLINE 200

/* print each line once, with the number of times it was repeated */
int main()
{
    char prev[MAXLINE], line[MAXLINE];
    int count;

    if (fgets(prev, MAXLINE, stdin) == NULL)
        return 0;
    count = 1;
    while (fgets(line, MAXLINE, stdin) != NULL)
        if (strcmp(line, prev) == 0)
            count++;
        else {
            printf("%4d %s", count, prev);
            strcpy(prev, line);
            count = 1;
        }
    printf("%4d %s", count, prev);
    return 0;
}

prev holds the line being counted. Each new line is either the same, which increments the count, or different, which prints the count and the previous line and starts a new count. The last line is printed after the loop. The program reads the first line before the loop, so that there is always a previous line to compare with; empty input prints nothing.

fruit.txt
pear
apple
plum
apple
fig
pear
apple
plum

The input has repeated lines that are not next to each other. sortlines brings them together, and its output goes through a pipe to uniq.

$ gcc -std=c89 -pedantic -Wall -Wextra -o uniq uniq.c
$ ./sortlines < fruit.txt | ./uniq
   3 apple
   1 fig
   2 pear
   2 plum

Splitting fields

Data often comes as lines of fields separated by commas. A program can split such a line in place: it replaces each comma by a '\0' and keeps pointers to the starts of the fields, so no characters are copied.

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

#define MAXLINE   200
#define MAXFIELDS 10

/* cut s at the commas; store the fields in f; return their number */
int split(s, f, max)
char *s, *f[];
int max;
{
    int n;

    n = 0;
    f[n++] = s;
    for (; *s != '\0'; s++)
        if (*s == ',' && n < max) {
            *s = '\0';
            f[n++] = s + 1;
        } else if (*s == '\n')
            *s = '\0';
    return n;
}

int main()
{
    char line[MAXLINE], *f[MAXFIELDS];
    double value, total;
    int n, lineno;

    total = 0.0;
    for (lineno = 1; fgets(line, MAXLINE, stdin) != NULL; lineno++) {
        n = split(line, f, MAXFIELDS);
        if (lineno == 1)
            continue;           /* the header line */
        if (n != 3) {
            fprintf(stderr, "line %d: %d fields\n", lineno, n);
            continue;
        }
        value = atoi(f[1]) * atof(f[2]);
        printf("%-10s %4s x %5s = %7.2f\n", f[0], f[1], f[2], value);
        total += value;
    }
    printf("%-10s %22.2f\n", "total", total);
    return 0;
}

split stores a pointer to the first field and then walks the line. Each comma ends a field and starts the next one, as long as there is room in f; the newline is cut off. The program skips the header line, checks that each line has three fields, and converts the count with atoi and the price with atof. This simple split does not handle quoted fields that contain commas.

stock.csv
item,count,price
pencil,120,0.35
notebook,40,2.10
eraser,75,0.50
ruler,30,1.25

The file lists items with their count and price.

$ gcc -std=c89 -pedantic -Wall -Wextra -o fields fields.c
$ ./fields < stock.csv
pencil      120 x  0.35 =   42.00
notebook     40 x  2.10 =   84.00
eraser       75 x  0.50 =   37.50
ruler        30 x  1.25 =   37.50
total                      201.00

Folding long lines

A line that is too long for the screen or the printer can be broken into several lines. A good place to break is a blank, so that no word is cut in two; a word longer than the line must be cut anyway.

fold.c
#include <stdio.h>
#include <string.h>

#define MAXLINE 500
#define WIDTH   40

/* print s in pieces of at most width characters, broken at blanks */
int fold(s, width)
char *s;
int width;
{
    int i, brk, c;

    while ((int) strlen(s) > width) {
        brk = 0;
        for (i = 1; i <= width; i++)
            if (s[i] == ' ')
                brk = i;        /* the last blank that fits */
        if (brk == 0)
            brk = width;        /* no blank: cut the word */
        c = s[brk];
        s[brk] = '\0';         /* end the piece for printf */
        printf("%s\n", s);
        s[brk] = c;
        s += brk;
        while (*s == ' ')
            s++;
    }
    printf("%s", s);
    return 0;
}

int main()
{
    char line[MAXLINE];

    while (fgets(line, MAXLINE, stdin) != NULL)
        fold(line, WIDTH);
    return 0;
}

While the rest of the line is longer than width, the loop looks for the last blank at or before the width. The piece before it is ended with a '\0', printed, and repaired; then the blanks after it are skipped. If there is no blank, the word is cut at the width. The last piece is printed with the newline that fgets kept.

long.txt
The first edition of the book described a small language that ran on the PDP-11 under UNIX, and on a few other machines.
Short lines pass through unchanged.
Averyveryverylongwordwithoutanyblankscannotbebrokenatablankatall and must be cut.

The input has a long line, a short line, and a line with a very long word.

$ gcc -std=c89 -pedantic -Wall -Wextra -o fold fold.c
$ ./fold < long.txt
The first edition of the book described
a small language that ran on the PDP-11
under UNIX, and on a few other
machines.
Short lines pass through unchanged.
Averyveryverylongwordwithoutanyblankscan
notbebrokenatablankatall and must be
cut.

Source

Dennis Ritchie: C Reference Manual (1975)

POSIX manual: fgets

In this article we have written text filters in K&R C: a pattern search with an exit status, trimming, sorting lines through an array of pointers, removing repeated lines in a pipe, splitting comma-separated fields, and folding long lines. Counting the words of a text is done by the word-frequency tree of the binary trees article, and replacing names by the table of the hash tables article. The next article shows how the storage allocator works.

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.