typestar

snprintf is the safe builder in C

snprintf bounds the write and tells you what the full length would have been.

#include <stdio.h>

int build_label(char *out, size_t cap, const char *lang, int tpm) {
    int needed = snprintf(out, cap, "%s at %d tpm", lang, tpm);
    if (needed < 0) {
        return -1;
    }
    return ((size_t) needed >= cap) ? 0 : 1;
}

void show(void) {
    char small[10];
    char roomy[64];

    printf("%d %s\n", build_label(small, sizeof small, "rust", 104), small);
    printf("%d %s\n", build_label(roomy, sizeof roomy, "rust", 104), roomy);
}

How it works

  1. It always terminates, as long as the size is non-zero.
  2. The return value is the length it wanted, so it detects truncation.
  3. That makes it the right tool for building any string.

Keywords and builtins used here

The run, in numbers

Lines
17
Characters to type
421
Tokens
134
Three-star pace
95 tpm

At the three-star pace of 95 tokens a minute, this run takes about 85 seconds.

Type this snippet

Step 2 of 4 in Copying & building, step 2 of 13 in Strings & text.

← Previous Next →