Name
snprintf
Synopsis
Stores formatted output in a string buffer
#include <stdio.h> intsnprintf( char * restrictdest, size_tn, const char * restrictformat, ... );
The snprintf() function is
similar to printf(), but writes
its output as a string in the buffer referenced by the first pointer
argument, dest, rather than to stdout. Furthermore, the second argument,
n, specifies the maximum number of
characters that snprintf() may
write to the buffer, including the terminating null character. If
n is too small to accommodate the
complete output string, then snprintf() writes only the first
n -1 characters of the output, followed
by a null character, and discards the rest. The return value is the
number of characters (not counting the terminating null character)
that would have been written if n had
been large enough. To obtain the length of the output string without
generating it, you can set n equal to
zero; in this case, sprintf()
writes nothing to dest, which may be a
null pointer.
Tip
If the output overlaps with any argument that snprintf() copies data from, the
behavior is undefined.
Example
char buffer[80];
double x = 1234.5, y = 678.9, z = -753.1, a = x * y + z;
int output_len = 0;
output_len =snprintf( buffer, 80, "For the input values %lf, %lf,"
" and %lf, the result was %lf.\n",
x, y, z, a );
puts( buffer );
if ( output_len >= 80 )
fprintf( stderr, "Output string truncated! Lost %d characters.\n",
output_len − 79 );This code produces the following output:
For the input values 1234.500000, ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access