snprintf() — Format and write data

Standards

Standards / Extensions C or C++ Dependencies
C99
Single UNIX Specification, Version 3
C++ TR1 C99
both z/OS® V1R6

Format

#define _ISOC99_SOURCE
#include <stdio.h>

int  snprintf(char *__restrict__ s, size_t n, const char *__restrict__ format, ...);
Note: The snprintf() function is also available under the alternate name __snprtf(). The __snprtf() function is accessible in the open name space.
#include <stdio.h>

int  __snprtf(char *__restrict__ s, size_t n, const char *__restrict__ format, ...);

General description

Equivalent to fprintf(), except that the output is written into an array (specified by argument s) rather than to a stream. If n is zero, nothing is written, and s may be a null pointer. Otherwise, output characters beyond the n-1st are discarded rather than being written to the array, and a null character is written at the end of the characters actually written into the array. If copying takes place between objects that overlap, the behavior is undefined.

Returned value

Returns the number of characters that would have been written had n been sufficiently large, not counting the terminating null character, or a negative value if an encoding error occurred. Thus, the null-terminated output has been completely written if and only if the returned value is nonnegative and less than n.

Errors

Function fails if:
  • The value of n is greater than {INT_MAX} or the number of bytes needed to hold the output excluding the terminating null is greater than {INT_MAX}. In this case, the function returns a negative value and sets errno to EOVERFLOW