Library contents

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

  1. Start with A three-byte buffer
  2. Do this Format the string AB
  3. Result 2 visible characters
There is room for A, B and the terminating zero. The return value counts the two visible characters.

Syntax

C 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.

First output lineAB-12
lesson.c
#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;
}
Output
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

Advertisements

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?

GivenLAB7 + terminator
Worked result5

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?

GivenP-104 + terminator
Worked result6