[Previous] [Contents] [Next]

snprintf()

Write formatted output to a character array, up to a given maximum number of characters

Synopsis:

#include <stdio.h>

int snprintf( char* buf,
              size_t count,
              const char* format, ... );

Library:

libc

Description:

The snprintf() function is equivalent to the fprintf() function, except that the argument buf specifies a character array (rather than a file) into which the generated output is placed. A null character is placed at the end of the generated character string.

The count variable specifies the maximum number of characters to store, including a terminating null character. The format string is described under the description of the printf() function.

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, although buf may be a null pointer.

If there's an output error, it returns a negative value and sets errno.

Examples:

#include <stdio.h>
#include <stdlib.h>

/* Create temporary file names using a counter */

char namebuf[13];
int  TempCount = 0;

char *make_temp_name( void )
{
    snprintf( namebuf, 13, "ZZ%.6o.TMP", 
              TempCount++ );
    return( namebuf );
}

int main( void )
{
    FILE *tf1, *tf2;

    tf1 = fopen( make_temp_name(), "w" );
    tf2 = fopen( make_temp_name(), "w" );
    fputs( "temp file 1", tf1 );
    fputs( "temp file 2", tf2 );
    fclose( tf1 );
    fclose( tf2 );

    return EXIT_SUCCESS;
}

Classification:

ANSI

Safety:
Cancellation point No
Interrupt handler No
Signal handler Yes
Thread Yes

See also:

errno, fprintf(), printf(), sprintf(), vfprintf(), vprintf(), vsprintf()


[Previous] [Contents] [Next]