Loading lessons...
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
| Function | Writes to |
|---|---|
printf | console (stdout) |
fprintf | any stream, e.g. a file |
sprintf | a char buffer |
snprintf | a char buffer, but bounded |
printf returns the number of chars printed. |
TL;DR
printfprints to the console.fprintfprints to a file or stream.sprintf/snprintfprint to a string (snprintf is the safe one).printfis really justfprintf(stdout, ...).