Back to Blog

C in 100 Seconds: sprintf and snprintf

Daryl WongDaryl Wong

Video: C in 100 Seconds: sprintf and snprintf — Format Into Strings | Episode 34 by Taught by Celeste AI - AI Coding Coach

Watch full page →

sprintf and snprintf

sprintf works like printf, but instead of printing to the screen, it writes the formatted text into a character buffer.

sprintf — Format Into a Buffer

char msg[100];
sprintf(msg, "Hello, %s! You are %d.", "Alice", 30);
// msg is now "Hello, Alice! You are 30."

Same format specifiers as printf — %s for strings, %d for integers, %03d for zero-padded numbers.

Building Filenames

char path[100];
int id = 7;
sprintf(path, "/tmp/file_%03d.txt", id);
// path is "/tmp/file_007.txt"

snprintf — The Safe Version

snprintf takes a size limit as the second argument. It will never write past the end of your buffer.

char small[15];
int n = snprintf(small, sizeof(small), "This is a very long string");
// small is "This is a very" (truncated at 14 chars + null)
// n is 26 (how many chars it needed)

The return value tells you how many characters it would have written — useful for detecting truncation.

sprintf vs snprintf

sprintf trusts you to provide a big enough buffer. If the formatted string is longer than the buffer, you get a buffer overflow. snprintf checks for you. In real code, always prefer snprintf.

Student Code

Try it yourself: episode34/format.c