SNPRINTF
Section: Linux Programmer's Manual (3)
Updated: 16 September 1995
NAME
snprintf, vsnprintf - formatted output conversion
SYNOPSIS
#define _GNU_SOURCE
#include <stdio.h>
int snprintf ( char *str, size_t n,
const char *format, ... );
#include <stdarg.h>
int vsnprintf ( char *str, size_t n,
const char *format, va_list ap );
DESCRIPTION
snprintf writes output to the string str, under control of
the format string that specifies how subsequent arguments are
converted for output. It is similar to sprintf(3), except that
n specifies the maximum number of characters to produce. The
trailing null character is counted towards this limit, so you should
allocate at least n characters for the string str.
vsnprintf is the equivalent of snprintf with the variable
argument list specified directly as for vprintf.
RETURN VALUE
If the output was truncated, the return value is -1, otherwise it is
the number of characters stored, not including the terminating null.
(Thus until glibc 2.0.6. Since glibc 2.1 these functions
return the number of characters (excluding the trailing null)
which would have been written to the final string if enough space
had been available.)
EXAMPLE
Here is an example program which dynamically enlarges its output buffer,
and works correctly under both glibc 2.0 and glibc 2.1.
/* Construct a message describing the value of a
variable whose name is NAME and whose value is
VALUE. */
char *
make_message (char *name, char *value)
{
/* Guess we need no more than 100 chars of space. */
int size = 100;
char *buffer = (char *) xmalloc (size);
while (1)
{
/* Try to print in the allocated space. */
int nchars = snprintf (buffer, size,
"value of %s is %s", name, value);
/* If that worked, return the string. */
if (nchars > -1 && nchars < size)
return buffer;
/* Else try again with more space. */
if (nchars > -1)
size = nchars+1; /* precisely what is needed */
else
size *= 2; /* twice the old size */
buffer = (char *) xrealloc (buffer, size);
}
}
CONFORMING TO
These are GNU extensions, expected to become part of ISO C9x.
SEE ALSO
printf(3), sprintf(3), vsprintf(3), stdarg(3)