Lesson 21 +10 XP

The printf Family

The printf Family

printf sends formatted output to the console. But it's part of a whole family in stdio.h.

sprintf: print to a string

sprintf writes formatted text into a char array instead of the console:

#include <stdio.h>

char buffer[50];
sprintf(buffer, "Age: %d", 25);
printf("%s\n", buffer);   // Age: 25

snprintf like sprintf but safe: it takes the buffer size and never writes past it.

fprintf: print to a file

fprintf prints to an output stream like a file:

FILE *file = fopen("log.txt", "w");
fprintf(file, "Error at line %d\n", 12);
fclose(file);

printf

And plain printf = fprintf(stdout, ...); the screen is just the standard output stream.

The family table

FunctionWrites to
printfconsole (stdout)
fprintfany stream, e.g. a file
sprintfa char buffer
snprintfa char buffer, but bounded
printf returns the number of chars printed.

TL;DR

  • printf prints to the console.
  • fprintf prints to a file or stream.
  • sprintf/ snprintf print to a string (snprintf is the safe one).
  • printf is really just fprintf(stdout, ...).