Updated: April 19, 2023 |
Write formatted output to a character array, up to a given maximum number of characters
#include <stdio.h> int snprintf( char* buf, size_t count, const char* format, ... );
libc
Use the -l c option to qcc to link against this library. This library is usually included automatically.
The snprintf() function generates a formatted string in the same way as fprintf(), except that snprintf() outputs the generated string into the character array pointed to by buf instead of writing it to a file. The snprintf() function is similar to sprintf(), but does boundary checking. Specifically, when count is nonzero, snprintf() copies at most count - 1 characters from the generated string (the remaining characters are discarded) into the output buffer and then appends a terminating null. When count is zero, nothing is written (and buf can be NULL).
The number of characters that would have been written into the array, not counting the terminating null character, had count been large enough. If the return value is equal to or greater than count, the string has been truncated.
If an error occurred, snprintf() returns a negative value and sets errno.
#include <stdio.h> #include <stdlib.h> /* Create temporary file names using a counter */ char namebuf[13]; int TempCount = 0; char *make_temp_name( void ) { snprintf( namebuf, 13, "ZZ%.6o.TMP", TempCount++ ); return( namebuf ); } int main( void ) { FILE *tf1, *tf2; tf1 = fopen( make_temp_name(), "w" ); tf2 = fopen( make_temp_name(), "w" ); fputs( "temp file 1", tf1 ); fputs( "temp file 2", tf2 ); fclose( tf1 ); fclose( tf2 ); return EXIT_SUCCESS; }
Safety: | |
---|---|
Cancellation point | No |
Interrupt handler | Yes |
Signal handler | Yes |
Thread | Yes |
Be careful if you're using snprintf() to build a string one piece at a time. For example, this code:
len += snprintf(&buf[len], RECSIZE - 1 - len, ...);
could have a problem if snprintf() truncates the string. Without a separate test to compare len with RECSIZE, this code doesn't protect against a buffer overflow. After the call that truncates the output, len is larger than RECSIZE, and RECSIZE - 1 - len is a very large (unsigned) number; the next call generates unlimited output somewhere beyond the buffer. It's better to use something like this:
len += snprintf(&buf[len], (len >= RECSIZE ? 0 : RECSIZE - 1 - len), ...);