puts(3)

C library function

Writes a string to standard output, then a newline. No format is interpreted, which makes it simpler than printf for printing fixed text.

Synopsis
#include <stdio.h>
int puts(const char *s);

Description

puts writes the string s to stdout, without its '\0', then adds a \n. It interprets nothing: a % in the text is printed as is, where printf(3) would see a conversion. Like printf, it goes through the stdout buffer, and the \n it adds is enough to flush it when output is a terminal.

GCC knows about this equivalence: even without optimization, it compiles printf("hello\n") into a call to puts("hello"). That is why a crash inside a printf sometimes shows up under the name puts in gdb.

Return value

A nonnegative number on success, EOF on error. Only the sign is guaranteed: do not use it as a length.

Pitfalls

  • The \n is added even if your string already ends with one: puts("line 1\n") leaves a blank line. To write a string without adding anything, use fputs(s, stdout).

  • puts(NULL) is undefined behavior. With glibc, the program crashes in strlen, which puts calls to measure the string.

  • The man page itself advises against mixing puts with direct calls to write(2) on the same output: the two do not share a buffer, and the display order is no longer guaranteed.

Example

fputs.c
#include <stdio.h>
int main(void){    puts("line 1\n");    fputs("line 2\n", stdout);    puts("100 % done");    return 0;}
Terminal
$ gcc -Wall -Wextra -g fputs.c -o fputs$ ./fputsline 1
line 2100 % done

The blank line comes from the double \n of the first call. fputs adds nothing, and the % on the last line goes through untouched.

C

puts

Write gm_puts with nothing but write: the string, then exactly one newline, even when the string is empty.

Open the exercise

Now write it yourself.