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
- It always terminates, as long as the size is non-zero.
- The return value is the length it wanted, so it detects truncation.
- That makes it the right tool for building any string.
Keywords and builtins used here
build_labelcharconstifintreturnshowsize_tsizeofvoid
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.
Step 2 of 4 in Copying & building, step 2 of 13 in Strings & text.