C snprintf
snprintf formats text into a bounded buffer and returns the number of characters it would have written, excluding the terminating null byte.
A simple example
snprintf
- Start with A three-byte buffer
- Do this Format the string AB
- Result 2 visible characters
Syntax
snprintf(buffer, sizeof buffer, format, ...)
Run this example in C
Save the program as lesson.c. Use C17 and a Unix-style shell.
cc -std=c17 -Wall -Wextra lesson.c -lm -o lesson
./lesson
Detect a truncated record label
A printed identifier has a prescribed width and may begin with zero. Verify the final text representation against the required field width before sending it to the label printer.
#include <stdio.h>
int main(void) {
char label[6];
int needed = snprintf(label, sizeof label, "%s-%d", "AB", 123);
if (needed < 0) return 1;
puts(label);
puts((size_t)needed >= sizeof label ? "truncated" : "complete");
return 0;
}
AB-12 truncated
Check for a negative result first. A nonnegative return value at least as large as the buffer means the full label did not fit, even though the stored prefix is terminated.
Open Group function reference for snprintf
Size a sample-label buffer
A lab printer needs to store a four-character code. Include room for a terminating zero byte when sizing this ASCII label buffer. How many bytes does the complete string require?
Size a parcel label buffer
A courier printer holds the identifier as a C-style string. Include room for a terminating zero byte when sizing this ASCII label buffer. How many bytes does the complete string require?