K&R C character input and output
last modified December 5, 2026 K&R C 1978
The simplest input and output in C works one character at a time. The
function getchar reads the next character from the standard
input, and putchar writes one character to the standard output.
Both come from the standard I/O library declared in
<stdio.h>. With just these two functions, the book builds
a series of small programs that copy and count text, the kind of programs
that UNIX is made of. This article writes its own versions of them.
Reading and writing characters
getchar returns the next input character each time it is
called. When there is no more input, it returns the value EOF,
which <stdio.h> defines. putchar(c) writes
the character c.
#include <stdio.h>
/* copy the input to the output one character at a time */
int main()
{
int c;
c = getchar();
while (c != EOF) {
putchar(c);
c = getchar();
}
return 0;
}
The program reads a character, and as long as it is not EOF,
writes it and reads the next one. The output is a copy of the input. The
variable c is an int, not a char; the
section The value of EOF explains why.
The programs in this article read the standard input, so they can read from
the keyboard, from a file, or from another program. When typing at the
keyboard, Ctrl-D at the start of a line ends the input on UNIX. Most
examples read this short text with the shell's <
redirection:
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 program does not know where its input comes from; the shell opens the file and connects it to the standard input before the program starts.
$ gcc -std=c89 -pedantic -Wall -Wextra -o copy copy.c $ ./copy < poem.txt 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.
Assignment in the loop test
In C an assignment is an expression with a value: the value assigned. The
call to getchar can therefore move into the test of the loop,
which removes the duplicated call before the loop.
#include <stdio.h>
/* copy the input, with the read inside the loop test */
int main()
{
int c;
while ((c = getchar()) != EOF)
putchar(c);
return 0;
}
(c = getchar()) != EOF reads a character, stores it in
c, and compares the stored value with EOF. This is
the usual form of the input loop in C. It is shorter, and the reading is
written in one place, which keeps the loop from getting out of step with
its input.
$ gcc -std=c89 -pedantic -Wall -Wextra -o copy_short copy_short.c $ echo 'Hello there!' | ./copy_short Hello there!
Precedence of the assignment
The parentheses around the assignment in the loop test are necessary. The
assignment operator has a lower precedence than !=, so without
them the comparison is done first.
#include <stdio.h>
/* the parentheses around the assignment are missing */
int main()
{
int c;
while (c = getchar() != EOF)
printf("%d ", c);
printf("\n");
return 0;
}
c = getchar() != EOF means c = (getchar() !=
EOF). The comparison yields 1 or 0, so c receives 1 for
every character and 0 at the end of the input, and the character itself is
lost. GCC suspects a mistake whenever an assignment is used as a condition
and asks for parentheses; with them, an intended assignment in a test is
written ((c = getchar())) or, better, compared explicitly.
$ gcc -std=c89 -pedantic -Wall -Wextra -o precedence precedence.c
precedence.c: In function ‘main’:
precedence.c:8:12: warning: suggest parentheses around assignment used as truth value [-Wparentheses]
8 | while (c = getchar() != EOF)
| ^
$ echo abc | ./precedence
1 1 1 1
The value of EOF
A character is a small integer: getchar returns the code of the
character in the machine's character set, ASCII on both of our machines.
EOF must be different from every character, so it is a value
outside the range of characters. <stdio.h> defines it
as -1.
#include <stdio.h>
/* print the code of every input character */
int main()
{
int c;
printf("EOF is %d\n", EOF);
while ((c = getchar()) != EOF)
printf("%d ", c);
printf("\n");
return 0;
}
The input AZ and the newline that echo adds give the
codes 65, 90, and 10. Programs should test for EOF by name
rather than by its value.
$ gcc -std=c89 -pedantic -Wall -Wextra -o codes codes.c $ echo AZ | ./codes EOF is -1 65 90 10
Why c is an int
A variable that receives the result of getchar must be able to
hold every character and EOF as well, so it must be bigger than
a char. A char variable cannot keep the two
apart.
#include <stdio.h>
/* c is a char: one input byte looks like EOF */
int main()
{
char c;
int n;
n = 0;
while ((c = getchar()) != EOF)
n++;
printf("%d characters read\n", n);
return 0;
}
The input has six bytes, one of them with the code 255, written
\377 in octal for the shell's printf command. Stored into a signed
char, 255 becomes -1, the same value as EOF, and
the loop stops after two characters. Where char is unsigned,
the opposite happens: -1 becomes 255, never equals EOF, and
the loop never ends. Plain ASCII text has no characters above 127, so the
mistake can go unnoticed for a long time.
$ gcc -std=c89 -pedantic -Wall -Wextra -o char_eof char_eof.c $ printf 'ab\377cd\n' | ./char_eof 2 characters read
Counting characters
The value returned by getchar does not have to be stored.
A program that only counts characters calls it in the loop test and throws
the character away.
#include <stdio.h>
/* count the characters of the input */
int main()
{
long n;
n = 0;
while (getchar() != EOF)
++n;
printf("%ld characters\n", n);
return 0;
}
The counter is a long, printed with %ld.
++n adds one to n; the
operators article covers the increment
operators. The empty lines between the stanzas count too: each line ends
with a newline character.
$ gcc -std=c89 -pedantic -Wall -Wextra -o chars chars.c $ ./chars < poem.txt 274 characters
Counting a large file
The size of an int depends on the machine, and a counter that
is fine for a short poem may be too small for a real file. The next program
counts the same input in an int and in a long.
#include <stdio.h>
/* count the characters in an int and in a long */
int main()
{
int small;
long big;
small = 0;
big = 0;
while (getchar() != EOF) {
++small;
++big;
}
printf("int: %d\n", small);
printf("long: %ld\n", big);
return 0;
}
The input is the word list of the system, a file of nearly a million
characters. On a machine with a 32-bit int both counters
agree.
$ gcc -std=c89 -pedantic -Wall -Wextra -o big_count big_count.c $ ./big_count < /usr/share/dict/words int: 985084 long: 985084
On the PDP-11 an int has 16 bits and holds at most 32767.
V7 UNIX keeps its own, smaller word list in /usr/dict, with
196513 characters. The long counter, 32 bits on the PDP-11,
gets them right. The int counter wraps around three times and
ends at 196513 - 3 × 65536 = -95. This is why the book counts characters in a
long.
$ cc big_count.c $ a.out < /usr/dict/words int: -95 long: 196513
Counting lines
A character written between single quotes, such as '\n', is a
character constant. Its value is the code of the character, and
it can be used wherever an integer can. Counting lines means counting
newline characters.
#include <stdio.h>
/* count the lines and the blank lines of the input */
int main()
{
int c, prev, lines, blank;
lines = 0;
blank = 0;
prev = '\n';
while ((c = getchar()) != EOF) {
if (c == '\n') {
++lines;
if (prev == '\n')
++blank;
}
prev = c;
}
printf("%d lines, %d blank\n", lines, blank);
printf("'\\n' is %d\n", '\n');
return 0;
}
A line is blank when its newline follows directly after the previous
newline. prev remembers the previous character; it starts as
'\n', so an empty first line counts as blank too. The last line
prints the value of the constant '\n', which is the integer 10.
$ gcc -std=c89 -pedantic -Wall -Wextra -o lines lines.c $ ./lines < poem.txt 9 lines, 1 blank '\n' is 10
Counting words
A word is a sequence of characters that are not blanks, tabs, or newlines. To count words, the program must remember whether it is inside a word or between words. Such a variable is called a state.
#include <stdio.h>
#define IN 1 /* inside a word */
#define OUT 0 /* between words */
/* count lines, words, and characters */
int main()
{
int c, state;
long lines, words, chars;
state = OUT;
lines = words = chars = 0;
while ((c = getchar()) != EOF) {
++chars;
if (c == '\n')
++lines;
if (c == ' ' || c == '\n' || c == '\t')
state = OUT;
else if (state == OUT) {
state = IN;
++words;
}
}
printf("%ld lines, %ld words, %ld characters\n",
lines, words, chars);
return 0;
}
A word begins when a character that is not white space comes while the state
is OUT; only then is the word counter incremented.
IN and OUT are symbolic constants, which make the
two states readable. The multiple assignment
lines = words = chars = 0 works because an assignment has a
value, and assignments group from right to left. The counts are the same as
those of the UNIX wc command.
$ gcc -std=c89 -pedantic -Wall -Wextra -o words words.c $ ./words < poem.txt 9 lines, 56 words, 274 characters
Converting characters
Because characters are integers, a program can compare them and compute with them. In ASCII the lower case letters have consecutive codes, and so do the upper case letters.
#include <stdio.h>
/* convert lower case letters to upper case */
int main()
{
int c;
while ((c = getchar()) != EOF) {
if (c >= 'a' && c <= 'z')
c = c - 'a' + 'A';
putchar(c);
}
return 0;
}
c >= 'a' && c <= 'z' tests for a lower case
letter. c - 'a' is the position of the letter in the alphabet,
and adding 'A' gives the upper case letter at the same
position. All other characters are copied unchanged. The program depends on
the letters being consecutive, which holds for ASCII but not for every
character set of the time; the strings article
shows the library functions that do not depend on it.
$ gcc -std=c89 -pedantic -Wall -Wextra -o upper upper.c $ echo 'Hello there, 42 times!' | ./upper HELLO THERE, 42 TIMES!
Squeezing blanks
A filter often needs to know the previous character to decide what to do with the current one. This program replaces every run of blanks and tabs with a single blank.
#include <stdio.h>
/* replace each run of blanks and tabs with one blank */
int main()
{
int c, prev;
prev = 'x';
while ((c = getchar()) != EOF) {
if (c == '\t')
c = ' ';
if (c != ' ' || prev != ' ')
putchar(c);
prev = c;
}
return 0;
}
A tab is turned into a blank first. A blank is written only if the previous
character was not a blank, so the first blank of a run is kept and the rest
are dropped. prev starts with any character that is not a
blank.
$ gcc -std=c89 -pedantic -Wall -Wextra -o squeeze squeeze.c $ printf 'too many \t blanks\n' | ./squeeze too many blanks
Pushing back a character
A program that reads a number cannot know that the number has ended until it
has read the first character after it. That character belongs to whatever
follows. The library function ungetc(c, stdin) pushes the
character c back onto the standard input, and the next call to
getchar returns it again. One character of push-back is
guaranteed.
#include <stdio.h>
/* read a number whose first digit is c */
int read_number(c)
int c;
{
int n;
n = 0;
while (c >= '0' && c <= '9') {
n = 10 * n + (c - '0');
c = getchar();
}
if (c != EOF)
ungetc(c, stdin); /* not a digit: give it back */
return n;
}
/* copy the input, doubling every number in it */
int main()
{
int c;
while ((c = getchar()) != EOF) {
if (c >= '0' && c <= '9')
printf("%d", 2 * read_number(c));
else
putchar(c);
}
return 0;
}
The program copies its input and doubles every number in it.
read_number receives the first digit, reads the rest, and
builds the value: c - '0' converts a digit character to its
value. The first character that is not a digit is pushed back, so the main
loop reads it and copies it. Without ungetc, the
g after the 250 would be lost. EOF is not pushed
back. The calculator article uses the same
idea with its own push-back buffer.
$ gcc -std=c89 -pedantic -Wall -Wextra -o doubler doubler.c $ echo 'Mix 2 eggs, 250g flour and 3 spoons of sugar.' | ./doubler Mix 4 eggs, 500g flour and 6 spoons of sugar.
Source
Dennis Ritchie: C Reference Manual (1975)
Linux manual: fgetc, getc, getchar, ungetc
In this article we have read and written single characters in K&R C:
getchar and putchar, the end of input
EOF and the int that holds it, programs that count
characters, lines, and words, character arithmetic, and
ungetc. The next article, K&R C
arrays, stores what these programs read. Modern C covers the same
functions in getchar and
ungetc.
Author
List all K&R C tutorials.