Previous Page
Next Page

snprintf

Stores formatted output in a string buffer

#include <stdio.h>
int snprintf ( char * restrict dest , size_t n ,
              const char * restrict format , ... );

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.

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, 678.900000, and -753.100000, the result was 8
Output string truncated! Lost 14 characters.

The first line was printed by snprintf( ) and the second by fprintf( ).

See Also

printf( ), fprintf( ), sprintf( ), declared in stdio.h; vprintf( ), vfprintf( ), vsprintf( ), vsnprintf( ), declared in stdarg.h; the wide-character functions: wprintf( ), fwprintf( ), swprintf( ), declared in stdio.h and wchar.h; and vwprintf( ), vfwprintf( ), and vswprintf( ), declared in stdarg.h; the scanf( ) input functions. Argument conversion in the printf( ) family of functions is described in detail under printf( ) in this chapter.


Previous Page
Next Page