snprintf, vsnprintf - formatted output conversion


     #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 );


     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.


     If the output was truncated, the return value is -1,  other-
     wise  it  is  the number of characters stored, not including
     the terminating null.


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


     These are GNU extensions.


     printf(3), sprintf(3), vsprintf(3),