putchar(3)

C library function

Writes one character to standard output, converted to unsigned char. Returns that character or EOF, and goes through the stdout buffer like printf.

Synopsis
#include <stdio.h>
int putchar(int c);

Description

putchar(c) writes a single character to standard output. It is exactly equivalent to putc(c, stdout), and its man page is shared with fputc, putc, fputs and puts: man 3 putchar shows puts(3).

The parameter is an int, but only one byte comes out: c is converted to unsigned char just before it is written. So putchar(321) writes A, since 321 = 256 + 65.

Like printf, putchar goes through the stdout buffer. The character is not necessarily on the screen when the call returns. It goes out when the buffer is flushed: at the end of a line if output is a terminal, when the buffer is full, at the end of the program, or on fflush(stdout).

Return value

The character written, converted to unsigned char and then to int, so a value from 0 to 255 on common machines. On error, EOF, and the error indicator of stdout is set. A success is never negative, which is what lets you test putchar(c) == EOF.

Note that what comes back is the byte written, not the argument: putchar(321) returns 65.

Pitfalls

  • Alternating putchar (or printf) and write(1, ...) on the same output can scramble the display order: write writes right away, putchar waits for the buffer. The man page explicitly advises against it. See the example below.

  • putchar('é') does not write an “é”. In UTF-8, é takes two bytes; GCC warns (multi-character character constant) and only one byte comes out. For accented text, use fputs("é", stdout).

  • putchar does not start a new line. For a string followed by a newline, use puts(3).

Example

return.c
#include <stdio.h>
int main(void){    int a = putchar('A');    int b = putchar(321);
    putchar('\n');    printf("%d %d\n", a, b);    return 0;}
Terminal
$ gcc -Wall -Wextra return.c -o return$ ./returnAA65 65

Both calls write A and return 65: of 321, only the low byte remains.

mixed.c
#include <stdio.h>#include <unistd.h>
int main(void){    putchar('1');    write(1, "2", 1);    putchar('3');    putchar('\n');    return 0;}
Terminal
$ gcc -Wall -Wextra mixed.c -o mixed$ ./mixed213

The 1 waits in the stdout buffer while write sends the 2 straight to the system; the final \n then flushes 1 and 3 together. The Grademe putchar exercise has you rewrite the function with write, with no buffer: each call writes its byte immediately.

C

putchar

Write gm_putchar with write on descriptor 1: it outputs one byte with no buffering and returns that byte as an int.

Open the exercise

Now write it yourself.