Safe Formatting with snprintf in C

Level 4178 keystrokes

Uses snprintf for safe string formatting with buffer size limit.

C code

// Small buffer to demonstrate truncation
1char buf[16];
// snprintf writes at most buffer size - 1 chars plus '\0'
// Returns number of chars that would have been written
2int written = snprintf(buf, sizeof(buf), "Score: %d pts", 12345);
// Prints the truncated text "Score: 12345 pt" (15 chars + '\0')
3printf("Buffer: %s\n", buf);
// Without the limit 16 chars would have been written (one did not fit)
4printf("Written: %d\n", written);
// Buffer size is 16
5printf("Size: %lu\n", sizeof(buf));

Output

Buffer: Score: 12345 pt
Written: 16
Size: 16
Practice typing this code

Practice typing this code. Results are not recorded in the rankings.

Symbols in this code

The symbols you type in this C code and how often they appear.

  • "× 8
  • ,× 6
  • (× 6
  • )× 6
  • ;× 5
  • :× 4
  • %× 4
  • \× 3
  • [× 1
  • ]× 1

More C examples at level 4

← C typing practice