On Linux it returns the number of characters that would be printed.
Is this standardized behavior?
snprintf ... Writes the results to a character string buffer. (...) will be terminated with a null character, unless buf_size is zero.
The snprintf() function formats and stores a series of characters and values in the array buffer. The snprintf() function accepts an argument 'n', which indicates the maximum number of characters (including at the end of null character) to be written to buffer.
The snprintf() function is identical to the sprintf() function with the addition of the n argument, which indicates the maximum number of characters (including the ending null character) to be written to buffer.
Yes.
From 7.21.6.5 The snprintf function, N1570 (C11 draft):
The snprintf function is equivalent to fprintf, except that the output is written into an array (specified by argument s) rather than to a stream. If n is zero, nothing is written, and s may be a null pointer. Otherwise, output characters beyond the n-1st are discarded rather than being written to the array, and a null character is written at the end of the characters actually written into the array. If copying takes place between objects that overlap, the behavior is undefined.
It's a useful method to find the length of unknown data for which you can first find the necessary length and then allocate the exact amount of memory. A typical use case is:
char *p;
int len = snprintf(0, 0, "%s %s some_long_string_here_", str1, str2);
p = malloc(len + 1);
snprintf(p, len + 1, "%s %s some_long_string_here", str1, str2);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With