On this page
snprintf
Prev: fprintf | Up: stdio.h | Next: vsnprintf
Rel: stdio.h, stdio.h & File I/O Guide
Ref: cppreference — snprintf
Tags: #public #prog #c #stdlib #stdio #tier/core
Include
#include <stdio.h>
Signature & Overview
int snprintf(char *restrict buf, size_t size, const char *restrict fmt, ...);
Bounds-checked formatted write into buf (at most size - 1 chars plus NUL terminator).
Notes & Pitfalls
- Always prefer
snprintf()oversprintf(): Guarantees NUL-termination (whensize > 0) and returns the would-be length so you can detect truncation (n < 0 || (size_t)n >= sizeof(buf)).
Example
#include <assert.h>
#include <stdio.h>
#include <string.h>
int main(void) {
char buf[16];
int n = snprintf(buf, sizeof(buf), "id=%d", 42);
assert(n > 0 && (size_t)n < sizeof(buf) && strcmp(buf, "id=42") == 0);
}
Linked from
Related notes
- tuts/c/stdlib/stdio/fprintf Linked here; links to this page; shared tags: #c, #prog, #stdio, #stdlib, #tier
- tuts/c/stdlib/stdio/vsnprintf Linked here; links to this page; shared tags: #c, #prog, #stdio, #stdlib, #tier
- tuts/c/stdlib/stdio Linked here; links to this page; shared tags: #c, #prog, #stdio, #stdlib
- tuts/c/stdlib/stdio/sprintf links to this page; shared tags: #c, #prog, #stdio, #stdlib, #tier
- tuts/c/stdlib/string/strcat links to this page; shared tags: #c, #prog, #stdlib, #tier
- tuts/c/stdlib/string/strcpy links to this page; shared tags: #c, #prog, #stdlib, #tier
- tuts/c/stdlib/string/strncpy links to this page; shared tags: #c, #prog, #stdlib, #tier
- tuts/c/stdlib/stdio_and_file_io Linked here; shared tags: #c, #prog, #stdlib
- tuts/c/stdlib/string links to this page; shared tags: #c, #prog, #stdlib
- tuts/c/stdlib/stdio/fclose shared tags: #c, #prog, #stdio, #stdlib, #tier