vsnprintf()

Write formatted output to a character array, up to a maximum number of characters (varargs)

Synopsis:

#include <stdarg.h>
#include <stdio.h>

int vsnprintf( char* buf,
               size_t count,
               const char* format,
               va_list arg );

Arguments:

buf
A pointer to the buffer where you want to function to store the formatted string.
count
The maximum number of characters to store in the buffer, including a terminating null character.
format
A string that specifies the format of the output. The formatting string determines what additional arguments you need to provide. For more information, see printf() .
arg
A variable-argument list of the additional arguments, which you must have initialized with the va_start() macro.

Library:

libc

Use the -l c option to qcc to link against this library. This library is usually included automatically.

Description:

The vsnprintf() function formats data under control of the format control string and stores the result in buf. The maximum number of characters to store, including a terminating null character, is specified by count.

The vsnprintf() function is a "varargs" version of snprintf() .

Returns:

The number of characters that would have been written into the array, not counting the terminating null character, had count been large enough. It does this even if count is zero; in this case buf can be NULL.

If an error occurred, vsnprintf() returns a negative value and sets errno .

Examples:

Use vsnprintf() in a general error message routine:

#include <stdio.h>
#include <stdarg.h>
#include <string.h>

char msgbuf[80];

char *fmtmsg( char *format, ... )
{
    va_list arglist;

    va_start( arglist, format );
    strcpy( msgbuf, "Error: " );
    vsnprintf( &msgbuf[7], 80-7, format, arglist );
    va_end( arglist );
    return( msgbuf );
}

int main( void )
{
    char *msg;

    msg = fmtmsg( "%s %d %s", "Failed", 100, "times" );
    printf( "%s\n", msg );

    return 0;
}

Classification:

ANSI, POSIX 1003.1

Safety:  
Cancellation point No
Interrupt handler No
Signal handler Read the Caveats
Thread Yes

Caveats:

It's safe to call vsnprintf() in a signal handler if the data isn't floating point.

Last modified: 2013-12-23

comments powered by Disqus