SNPRINTF(3)

NAME
snprintf, vsnprintf - formatted output conversion

SYNOPSIS
#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
The return value is the number of characters stored, not including the terminating null. If this value equals n, then there was not enough space in str for all the output. You should try again with a bigger output string.

EXAMPLES
Here is an example program which dynamically enlarges its output buffer.

    /* 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 < size)
            return buffer;
          /* Else try again with twice as much space. */
          size *= 2;
          buffer = (char *) xrealloc (size, buffer);
        }
    }

CONFORMING TO
These are GNU extensions.

SEE ALSO
printf(3), sprintf(3), vsprintf(3), stdarg(3)