Computer Science


SNPRINTF(3)         Linux Programmer's Manual         SNPRINTF(3)

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, oth-
       erwise it is the number of characters stored, not  includ-
       ing the terminating null.

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

CONFORMING TO
       These are GNU extensions.

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

GNU                     16 September 1995                       1

Back to the index


Apply now!


Handbook

Postgraduate study options

Computer Science Blog



Please give us your feedback or ask us a question

This message is...


My feedback or question is...


My email address is...

(Only if you need a reply)

A to Z Directory | Site map | Accessibility | Copyright | Privacy | Disclaimer | Feedback on this page