sprintf() — Format and Write Data

Format

#include <stdio.h>

int sprintf(char *__restrict__buffer, const char *__restrict__format-string, …);

General Description

The sprintf() function formats and stores a series of characters and values in the array pointed to by buffer. Any argument-list is converted and put out according to the corresponding format specification in the format-string. If the strings pointed to by buffer and format-string overlap, behavior is undefined.

The format-string consists of ordinary characters, escape sequences, and conversion specifications. The ordinary characters are copied in order of their appearance. Conversion specifications, beginning with a percent sign (%) or the sequence (%n$) where n is a decimal integer in the range [1,NL_ARGMAX], determine the output format for any argument-list following the format-string. The format-string can contain multibyte characters beginning and ending in the initial shift state. When the format-string includes the use of the optional prefix ll to indicate the size expected is a long long datatype then the corresponding value in the argument list should be a long long datatype if correct output is expected.
  • If the %n$ conversion specification is found, the value of the nth argument after the format-string is converted and output according to the conversion specification. Numbered arguments in the argument list can be referenced from format-string as many times as required.
  • The format-string can contain either form of the conversion specification, that is, % or %n$ but the two forms cannot be mixed within a single format-string except that %% can be mixed with the %n$ form. When numbered conversion specifications are used, specifying the 'nth' argument requires that the first to (n-1)th arguments are specified in the format-string.

The format-string is read from left to right. When the first format specification is found, the value of the first argument after the format-string is converted and output according to the format specification. The second format specification causes the second argument after the format-string to be converted and output, and so on through the end of the format-string. If there are more arguments than there are format specifications, the extra arguments are evaluated and ignored. The results are undefined if there are not enough arguments for all the format specifications. The format specification is illustrated below.

Read syntax diagramSkip visual syntax diagram
Format Specification for sprintf()

>>-%--+-------+--+-------+--+--------------+--+----+--type-----><
      '-flags-'  '-width-'  '-.--precision-'  +-h--+         
                                              +-hh-+         
                                              +-j--+         
                                              +-l--+         
                                              +-ll-+         
                                              +-L--+         
                                              +-t--+         
                                              '-z--'         

Each field of the format specification is a single character or number signifying a particular format option. The type character, which appears after the last optional format field, determines whether the associated argument is interpreted as a character, a string, a number, or pointer. The simplest format specification contains only the percent sign and a type character (for example, %s).

The percent sign: If a percent sign (%) is followed by a character that has no meaning as a format field, the character is simply copied to the buffer. For example, to print a percent sign character, use %%.
The flag characters: The flag characters in Table 1 are used for the justification of output and printing of thousands of grouping characters, signs, blanks, decimal-points, octal prefixes, and hexadecimal prefixes. Note that more than one flag can appear in a format specification. This is an optional field.
Table 1. Flag Characters for sprintf() Family
Flag Meaning Default
' The integer portion of the result of a decimal conversion (%i,%d,%u, %f,%g or %G) will be formatted with the thousands' grouping characters. No grouping.
- Left-justify the result within the field width. Right-justify.
+ Prefix the output value with a sign (+ or -) if the output value is of a signed type. Sign appears only for negative signed values (-).
blank(' ') Prefix the output value with a blank if the output value is signed and positive. The + flag overrides the blank flag if both appear, and a positive signed value will be output with a sign. No blank.
# When used with the o, x, or X formats, the # flag prefixes any nonzero output value with 0, 0x, or 0X, respectively.

For o conversion, it increases the precision, if necessary, to force the first digit of the result to be a zero. If the value and precision are both 0, a single 0 is printed.

For e, E, f, F, g , and G conversion specifiers, the result always contains a decimal-point, even if no digits follow the decimal-point. Without this flag, a decimal-point appears in the result of these conversions only if a digit follows it.

For g and G conversion specifiers, do not remove trailing zeros from the result as they normally are. For other conversion specifiers, the behavior is undefined.

No prefix.
0 When used with the d, i, o, u, x, X, e, E, f, F, g , or G conversion specifiers, leading zeros are used to pad to the field width. If the 0 and - flags both appear, the 0 flag is ignored.

For d, i, o, u, x, and X conversion specifiers, if a precision is specified, the 0 flag is ignored.

If the 0 and ' flags both appear, the grouping characters are inserted before zero padding. For other conversions, the behavior is undefined.

Space padding.

The code point for the # character varies between the EBCDIC encoded character sets. The Metal C runtime library expects the # character to use the code point for encoded character set IBM-1047.

The # flag should not be used with c, d, i, u, s, or p types.

The Width of the Output: Definition of the width specification is as follows.

Width is a nonnegative decimal integer controlling the minimum number of characters printed. If the number of characters in the output value is less than the specified width, blanks are added on the left or the right (depending on whether the flag is specified) until the minimum width is reached.

Width never causes a value to be truncated; if the number of characters in the output value is greater than the specified width, or width is not given, all characters of the value are output (subject to the precision specification).

The width specification can be an asterisk (*); if it is, an argument from the argument list supplies the value. The width argument must precede the value being formatted in the argument list. This is an optional field.

If format-string contains the %n$ form of conversion specification, width can be indicated by the sequence *m$, where m is a decimal integer in the range [1,NL_ARGMAX] giving the position of an integer argument in the argument list containing the field width.

The Precision of the Output: Definition of the precision specification is as follows.

The precision specification is a nonnegative decimal integer preceded by a period. It specifies the number of characters to be output, or the number of decimal places. Unlike the width specification, the precision can cause truncation of the output value.

The precision specification can be an asterisk (*); if it is, an argument from the argument list supplies the value. The precision argument must precede the value being formatted in the argument list. The precision field is optional.

If format-string contains the %n$ form of conversion specification, precision can be indicated by the sequence *m$, where m is a decimal integer in the range [1,NL_ARGMAX] giving the position of an integer argument in the argument list containing the field precision.

The interpretation of the precision value and the default when the precision is omitted depend upon the type, as shown in Table 2.

Table 2. Precision Argument in sprintf()
Type Meaning Default

   d
   i
   o
   u
   x
   X

Precision specifies the minimum number of digits to be output. If the number of digits in the argument is less than precision, the output value is padded on the left with zeros. The value is not truncated when the number of digits exceeds precision. Default precision is 1. If precision is 0, or if the period (.) appears without a number following it, the precision is set to 0. When precision is 0, conversion of the value zero results in no characters.

   c

No effect. The character is output.

   s

Precision specifies the maximum number of characters to be output. Characters in excess of precision are not output. Characters are output until a NULL character is encountered.

e
E
f
F

Precision specifies the number of digits to be output after the decimal-point. The last digit output is rounded. Default precision is 6. If precision is 0 or the period appears without a number following it, no decimal-point is output.

g
G

Precision specifies the maximum number of significant digits output. All significant digits are output.
Optional prefix: Used to indicate the size of the argument expected.
h
A prefix with the integer types d, i, o, u, x, X means the integer is 16 bits long.
hh
Specifies that a following d, i, o, u, x, or X conversion specifier applies to a signed char or unsigned char argument (the argument will have been promoted according to the integer promotions, but its value shall be converted to signed char or unsigned char before printing); or that a following n conversion specifier applies to a pointer to a signed char argument.
j
Specifies that a following d, i, o, u, x, or X conversion specifier applies to an intmax_t or uintmax_t argument; or that a following n conversion specifier applies to a pointer to an intmax_t argument.
l
A prefix with d, i, o, u, x, X, and n types that specifies that the argument is a long int or unsigned long int.
ll
A prefix with the integer types d, i, o, u, x, X means the integer is 64 bits long.
L
A prefix with e, E, f, g, or G types that specifies that the argument is long double.
t
Specifies that a following d, i, o, u, x, or X conversion specifier applies to a ptrdiff_t or the corresponding unsigned type argument; or that a following n conversion specifier applies to a pointer to a ptrdiff_t argument.
z
Specifies that a following d, i, o, u, x, or X conversion specifier applies to a size_t or the corresponding signed integer type argument; or that a following n conversion specifier applies to a pointer to a signed integer type corresponding to a size_t argument.

Table 3 below shows the meaning of the type characters used in the precision argument.

Table 3. Type Characters and their Meanings
Type Argument Output Format

d, i

Integer Signed decimal integer.

u

Integer Unsigned decimal integer.

o

Integer Unsigned octal integer.

x

Integer Unsigned hexadecimal integer, using abcdef.

X

Integer Unsigned hexadecimal integer, using ABCDEF.

c

Character

Single character.

s

String

Characters output up to the first NULL character (\0) or until precision is reached.

n

Pointer to integer Number of characters successfully output so far to the stream or buffer; this value is stored in the integer whose address is given as the argument.

p

Pointer Pointer to void converted to a sequence of printable characters. See the individual system reference guides for the specific format.

f, F

Double Signed value having the form [-]dddd.dddd, where dddd is one or more decimal digits. The number of digits before the decimal-point depends on the magnitude of the number. The number of digits after the decimal-point is equal to the requested precision. If the precision is explicitly zero and no # is present, no decimal-point appears. If a decimal-point appears, at least one digit appears before it.

Convert a double argument representing an infinity in [+/-]inf: a plus or minus sign with the character sequence inf, followed by a white space character (space, tab, or newline), a NULL character (\0), or EOF.

Convert a double argument representing a NaN in one of the styles:
  • [+/-]nan(n) for a signaling nan.
  • [+/-nanq(n)] for a quiet nan, where n is an integer and 1<= n<= INT_MAX-1.

The value of n is determined by the fraction bits of the NaN argument value. For a signaling NaN value, NaN fraction bits are reversed (left to right) to produce bits (right to left) of an even integer value, 2*n. For a quiet NaN value, NaN fraction bits are reversed (left to right) to produce bits (right to left) of an odd integer value, 2*n-1.

The F conversion specifier produces INFe, NANS, or NANQ instead of infQ, nans or, nanq respectively.

e, E

Double Signed value having the form [-]d.dddde[ sign]ddd:
  • d is a single-decimal digit.
  • dddd is one or more decimal digits.
  • ddd is 2 or more decimal digits.
  • sign is + or -.
If the precision is zero and no # flag is present, no decimal-point appears. The conversion specifier produces a number with E instead of e to introduce the exponent.

A double argument representing an infinity or NaN is converted in the style of an f or F conversion specifier.

g, G

Double Signed value output in f or e format (or in the F or E format in the case of a G conversion specifier). The e or E format is used only when the exponent of the value is less than -4 or greater than or equal to the precision. Trailing zeros are truncated, and the decimal-point appears only if one or more digits follow it or a # flag is present.

A double argument representing an infinity or NaN is converted in the style of an f or F conversion specifier.

Returned Value

If successful, sprintf() returns the number of characters output. The ending NULL character is not counted.

If unsuccessful, sprintf() returns a negative value.

Related Information