fprintf(), printf(), sprintf() — Format and write data

Standards

Standards / Extensions C or C++ Dependencies

C/C++ DFP
ISO C
POSIX.1
XPG4
XPG4.2
C99
Single UNIX Specification, Version 3
Language Environment

both z/OS® V1.8

Format

#include <stdio.h>

int fprintf(FILE *__restrict__stream, const char *__restrict__format-string, …);
int printf(const char *__restrict__format-string, …);
int sprintf(char *__restrict__buffer, const char *__restrict__format-string, …);

#define _OPEN_SYS_UNLOCKED_EXT 1
#include <stdio.h>

int fprintf_unlocked(FILE *__restrict__stream, 
                     const char *__restrict__format-string, …);
int printf_unlocked(const char *__restrict__format-string, …);

General description

These three related functions are referred to as the fprintf family.

The fprintf() function formats and writes output to a stream. It converts each entry in the argument list, if any, and writes to the stream according to the corresponding format specification in the format-string. The fprintf() function cannot be used with a file that is opened using type=record or type=blocked.

The printf() function formats and writes output to the standard output stream stdout. printf() cannot be used if stdout has been reopened using type=record or type=blocked.

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 overlap, behavior is undefined.

fprintf() and printf() have the same restriction as any write operation for a read immediately following a write or a write immediately following a read. Between a write and a subsequent read, there must be an intervening flush or reposition. Between a read and a subsequent write, there must also be an intervening flush or reposition unless an EOF has been reached.

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.

fprintf_unlocked() is functionally equivalent to fprintf() with the exception that it is not thread-safe. This function can safely be used in a multithreaded application if and only if it is called while the invoking thread owns the (FILE*) object, as is the case after a successful call to either the flockfile() or ftrylockfile() function.

printf_unlocked() is functionally equivalent to printf() with the exception that it is not thread-safe. This function can safely be used in a multithreaded application if and only if it is called while the invoking thread owns the (FILE*) object, as is the case after a successful call to either the flockfile() or ftrylockfile() function.

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 fprintf(), printf(), and sprintf()

>>-%--+-------+--+-------+--+--------------+--+----+------------>
      '-flags-'  '-width-'  '-.--precision-'  +-h--+   
                                              +-hh-+   
                                              +-l--+   
                                              +-ll-+   
                                              +-j--+   
                                              +-t--+   
                                              +-z--+   
                                              +-D--+   
                                              +-DD-+   
                                              +-H--+   
                                              '-L--'   

>--conversion specifier----------------------------------------><

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).

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 stdout. For example, to print a percent sign character, use %%.

Flag characters: The flag characters in Table 1 are used for the justification of output and printing of thousands' grouping characters, signs, blanks, decimal-points, octal, and hexadecimal prefixes, and the semantics for wchar_t precision unit. Notice that more than one flag can appear in a format specification. This is an optional field.
Table 1. Flag Characters for fprintf Family
Flag Meaning Default
' Added for XPG4: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 and only 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 will be printed)

No prefix.
When used with the f, e, or E formats, the # flag forces the output value to contain a decimal-point in all cases.

The decimal-point is sensitive to the LC_NUMERIC category of the same current locale.

Decimal-point appears only if digits follow it.
When used with the g or G formats, the # flag forces the output value to contain a decimal-point in all cases and prevents the truncation of trailing zeros. Decimal-point appears only if digits follow it; trailing zeros are truncated.
When used with the ls or S format, the # flag causes precision to be measured in wide characters. Precision indicates the maximum number of bytes to be output.
0 When used with the d, i, o, u, x, X, e, E, f, g, or G formats, the 0 flag causes leading 0's to pad the output to the field width. The 0 flag is ignored if precision is specified for an integer or if the - flag is specified. Space padding.

The code point for the # character varies between the EBCDIC encoded character sets. The definition of the # character is based on the current LC_SYNTAX category. The default C locale expects the # character to use the code point for encoded character set IBM-1047.

When the LC_SYNTAX category is set using setlocale(), the format strings passed to the printf() functions must use the same encoded character set as is specified for the LC_SYNTAX category.

The # flag should not be used with c, lc, C, d, i, u, s, or p conversion specifier.

Output width: The width argument 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.

The 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.

Output precision: The precision argument 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 or rounding of a floating-point value.

Be aware that the rounding of floating-point values may not always occur as expected based on the decimal value of the number. This is because the internal binary representation cannot always be an exact representation of the decimal value, so the rounding may occur on an inexact value. This is true of both OS/390® hexadecimal and IEEE 754 binary floating- point formats.

The precision argument 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 fprintf Family
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.

   e
   E
   f
   F

Precision specifies the number of digits to be output after the decimal-point. The last digit output is rounded.

The decimal-point is sensitive to the LC_NUMERIC category of the current locale.

Default precision is 6. If precision is 0 or the period appears without a number following it, no decimal-point is output.

   a
   A

For non decimal floating-point numbers, precision specifies the number of hexadecimal digits to be output after the decimal-point character.

For decimal floating-point numbers, precision determines the style of formatting to be used.

For non decimal floating-point numbers, default precision is 6. If precision is 0, no decimal-point is output.

For decimal floating-point numbers, precision is determined by the quantum of the decimal floating-point number. Refer to Table 3 for more details.

   g
   G

Precision specifies the maximum number of significant digits output. All significant digits are output.

   c

No effect. The character is output.

   C
   lc

No effect. The wide 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.

   S
   ls

Precision specifies the maximum number of bytes to be output. Bytes in excess of precision are not output; however, multibyte integrity is always preserved. wchar_t characters are output until a NULL character is encountered.
Optional prefix: The optional prefix characters used to indicate the size of the argument expected are explained:
Prefix
Meaning
h
Specifies that the d, i, o, u, x, or X conversion specifier applies to a short or unsigned short argument (the argument will have been promoted according to the integer promotions, but its value shall be converted to short or unsigned short before printing); or that a following n conversion specifier applies to a pointer to a short argument.
hh
Specifies that the 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.
l
(ell) Specifies that the d, i, o, u, x, or X conversion specifier applies to a long or unsigned long argument; that a following n conversion specifier applies to a pointer to a long argument; that the c conversion specifier applies to a wint_t argument; that the s conversion specifier applies to a pointer to a wchar_t argument. It has no effect on the a, A, e, E, f, F, g, or G conversion specifier.
ll
(ell-ell) Specifies that the d, i, o, u, x, or X conversion specifier applies to a long long or unsigned long long argument; or that the n conversion specifier applies to a pointer to a long long argument.
j
Specifies that the d, i, o, u, x, or X conversion specifier applies to an intmax_t or uintmax_t argument; or that the n conversion specifier applies to a pointer to an intmax_t argument.
t
Specifies that the d, i, o, u, x, or X conversion specifier applies to a ptrdiff_t or the corresponding unsigned type argument; or that the n conversion specifier applies to a pointer to a ptrdiff_t argument.
z
Specifies that the d, i, o, u, x, or X conversion specifier applies to a size_t or the corresponding signed integer type argument; or that the n conversion specifier applies to a pointer to a signed integer type corresponding to a size_t argument.
D
Specifies that the a, A, e, E, f, F, g, or G conversion specifier applies to an _Decimal64 argument.
DD
Specifies that the a, A, e, E, f, F, g, or G conversion specifier applies to an _Decimal128 argument.
H
Specifies that the a, A, e, E, f, F, g, or G conversion specifier applies to an _Decimal32 argument.
L
Specifies that the a, A, e, E, f, F, g, or G conversion specifier applies to a long double argument.

Conversion specifier: Table 3 explains the meaning of the type characters used in the precision argument.

Table 3. Type Characters and their Meanings
Conversion specifier 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.
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.

The decimal-point is sensitive to the LC_NUMERIC category of the current locale.

e Double Signed value having the form [-]d.dddde[ sig n]ddd, where d is a single-decimal digit, dddd is one or more decimal digits, ddd is 2 or more decimal digits, and sign is + or -.

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

E Double Identical to the e format, except that E introduces the exponent, not e.
g Double Signed value output in f or e format. The 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.

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

G Double Identical to the g format, except that E introduces the exponent (where appropriate), not e.
D(n,p) Decimal type argument. Fixed-point value consisting of a series of one or more decimal digits possibly containing a decimal-point.

c
C or lc

Character
Wide Character

Single character.

The argument of wchar_t type is converted to an array of bytes representing a multibyte character as if by call to wctomb().

s
S or ls

String
Wide String

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

The argument is a pointer to an array of wchar_t type. Wide characters from the array are converted to multibyte characters up to and including a terminating NULL wide character. Conversion takes place as if by a call to wcstombs(), with the conversion state described by the mbstate_t object initialized to 0. The result written out will not include the terminating NULL character.

If no precision is specified, the array contains a NULL wide character. If a precision is specified, its sets the maximum number of characters written, including shift sequences. A partial multibyte character cannot be written.

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. Refer to the individual system reference guides for the specific format.
a, A

Double
_Decimal32
_Decimal64
_Decimal128

A double argument representing a floating-point number is converted to the "[-]0xh.hhhhp±d" format, where there is one hexadecimal digit (non-zero when the argument is a normalized floating-point number; otherwise unspecified) before the decimal-point character and the number of hexadecimal digits after it is equal to the precision. If the precision is missing and FLT_RADIX is a power of 2, then the precision will be sufficient for an exact representation of the value. If the precision is missing and FLT_RADIX is not a power of 2, then the precision will be sufficient to distinguish values of type double, except that trailing zeros may be omitted. If the precision is zero and the "#" flag is not specified, no decimal-point will appear. The letters "abcdef" are used for the a conversion and the letters "ABCDEF" for the A conversion. The A conversion specifier produces a number with letters "X" and "P" instead of letters "x" and "p". The exponent always contains at least one digit, and only as many more digits as necessary to represent the decimal exponent of 2. If the value is zero, the exponent is zero.

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

If precision is zero, results can be different for Hexadecimal floating point format and IEEE floating point format. For Hexadecimal floating point, a decimal point will not appear in the output. For IEEE floating point, a decimal point will appear.

If an H, D, or DD modifier is present and the precision is missing, then for a decimal floating type argument, either the f or e style formatting is used based on the following criteria:
  • f style formatting is used when the quantum is less than or equal to 0 but greater than or equal to -(n+5). The quantum of a number can be determined by calling the quantexp() functions. The number of digits (n) in the digit-sequence includes trailing zeros only and ignores the decimal point. For example:
    0.000005
    contains 1 digit in the digit sequence, n = 1
    0.0000050
    contains 2 digits in the digit sequence, n = 2
    12.30
    contains 4 digits in the digit sequence, n = 4
    The precision is equal to -quantum.
  • e style formatting is used when the quantum does not satisfy the f style criteria. The precision is equal to n-1, except if the argument is equal to 0 then the digit-sequence in the exponent-part is equal to the quantum. For example:
    0.0000000
    produces 0e-07
    -1870
    produces -1.87e+03
    \If the precision is present and at least as large as the precision of the decimal floating type, the conversion is as if the precision were missing. If the precision is present and less than the precision of the decimal floating type, the input is first rounded according to the current rounding direction to the number of digits specified by the precision . The result is then converted as if the precision were missing.

The "quantum" when referring to a finite decimal floating-point number is defined as the "magnitude of a value of one in the rightmost digit position of the significand". For example, pennies and dollars can be represented respectively as 1 * 10 with a quantum of -2 and 0, or, 1*10^-2 and 1*10^0. For more information on the term quantum, see z/Architecture Principles of Operation.

Special behavior for XPG4:
  • 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.

Floating-point and the fprintf family of formatted output functions: The fprintf family functions match a, A, e, E, f, F, g, or G conversion specifiers to floating-point arguments for which they produce floating-point number substrings in the output stream. The fprintf family functions have been extended to determine the floating-point format, hexadecimal floating-point or IEEE Binary Floating-Point, of types a, A, e, E, f, F, g, or G by using __isBFP().

The fprintf family functions convert IEEE Binary Floating-Point infinity and NaN argument values to special infinity and NaN floating-point number output sequences.

The C99 standard does not distinguish between the quiet NaN and signaling NaN values. An argument representing a NaN (Not a Number) is to be displayed as [-]nan or [-]nan(n-char-sequence); where the implementation decides the representation. For the A, E, F, and G conversion specifiers, NaN values are displayed as the uppercase versions of the aforementioned character string representations. To get this behavior set the environment variable _EDC_C99_NAN to YES.

Some compatibility with NaN sequences output by AIX formatted output functions can be achieved by setting a new environment variable, _AIX_NAN_COMPATIBILITY, which z/OS formatted output functions recognize, to one of the following (string) values:

Value
Output function
1
Formatted output functions which produce special NaN output sequences omit the NaN ordinal output sequence (1). This results in output NaN sequences of plus or minus sign followed by NANS or NANQ instead of plus or minus sign followed by NANS(1) or NANQ(1). All other NaN ordinal sequences are explicitly output.
ALL
Formatted output functions which produce special NaN output sequences omit the NaN ordinal output sequence for all NaN values. This results in output NaN sequences of plus or minus sign followed by NANS or NANQ instead of plus or minus sign followed by NANS(n) or NANQ(n) for all NaN values.
Note: _AIX_NAN_COMPATIBILITY does not affect the formatting of DFP NAN values. It affects only the formatting of BFP NAN values.

The sprintf() function is available to C applications in a stand-alone System Programming C (SPC) Environment.

Usage notes

  1. FLOAT(HEX) normalizes differently than FLOAT(IEEE). FLOAT(HEX) produces output in 0x0.hhhhhp+/-dd format, not in the 0x1.hhhhhhp+/-dd format.
  2. To use IEEE decimal floating-point, the hardware must have the Decimal Floating-Point Facility installed.

Returned value

If successful, fprintf(), printf(), and sprintf() return the number of characters output. The ending NULL character is not counted.

If unsuccessful, they return a negative value.

Example

CELEBF30
⁄* CELEBF30                                      

   This example prints data using &printf. in a variety of                      
   formats.                                                                     
                                                                                
 *⁄                                                                             
#include <stdio.h>                                                              
                                                                                
int main(void)                                                                  
{                                                                               
   char ch = 'h', *string = "computer";                                         
   int count = 234, hex = 0x10, oct = 010, dec = 10;                            
   double fp = 251.7366;                                                        
   unsigned int a = 12;                                                         
   float b = 123.45;                                                            
   int c;                                                                       
   void *d = "a";                                                               
                                                                                
   printf("the unsigned int is %u\n\n",a);                                      
                                                                                
   printf("the float number is %g, and %G\n\n",b,b);                            
                                                                                
   printf("RAY%n\n\n",&c);                                                      
                                                                                
   printf("last line prints %d characters\n\n",c);                              
                                                                                
   printf("Address of d is %p\n\n",d);                                          
                                                                                
   printf("%d   %+d    %06d     %X    %x     %o\n\n",                           
      count, count, count, count, count, count);                                
                                                                                
   printf("1234567890123%n4567890123456789\n\n", &count);                       
                                                                                
   printf("Value of count should be 13; count = %d\n\n", count);                
                                                                                
   printf("%10c%5c\n\n", ch, ch);                                               
                                                                                
   printf("%25s\n%25.4s\n\n", string, string);                                  
                                                                                
   printf("%f    %.2f    %e    %E\n\n", fp, fp, fp, fp);                        
                                                                                
   printf("%i    %i     %i\n\n", hex, oct, dec);                                
}                                                                               
Output
the unsigned int is 12

the float number is 123.45 and 123.45

RAY

last line prints 3 characters

Address of d is DD72F9

234   +234    000234     EA    ea     352

12345678901234567890123456789

Value of count should be 13; count = 13

         h    h

                 computer
                     comp

251.736600    251.74    2.517366e+02    2.517366E+02

16    8     10
CELEBF31
/* CELEBF31
   The following example illustrates the use of printf() to print
   fixed-point decimal data types.
   This example works under C only, not C++.
 */
#include <stdio.h>
#include <decimal.h>

decimal(10,2) pd01 = -12.34d;
decimal(12,4) pd02 = 12345678.9876d;
decimal(31,10) pd03 = 123456789013579246801.9876543210d;

int main(void) {
  printf("pd01 %%D(10,2)      = %D(10,2)\n", pd01);
  printf("pd02 %%D( 12 , 4 )  = %D( 12 , 4 )\n", pd02);

  printf("pd01 %%010.2D(10,2) = %010.2D(10,2)\n", pd01);
  printf("pd02 %%20.2D(12,4)  = %20.2D(12,4)\n", pd02);
  printf("\n Give strange result if the specified size is wrong!\n");
  printf("pd03 %%D(15,3)      = %D(15,3)\n\n", pd03);
}
Output
pd01 %D(10,2)      = -12.34
pd02 %D( 12 , 4 )  = 12345678.9876
pd01 %010.2D(10,2) = -000012.34
pd02 %20.2D(12,4)  =          12345678.98

Give strange result if the specified size is wrong!
pd03 %D(15,3)      = -123456789013.579
CELEBF32
/* CELEBF32
   This example illustrates the use of sprintf() to format and print
   various data.
 */
#include <stdio.h>

char buffer[200];
int i, j;
double fp;
char *s = "baltimore";
char c;

int main(void)
{
   c = 'l';
   i = 35;
   fp = 1.7320508;

   /* Format and print various data */
   j = sprintf(buffer, "%s\n", s);
   j += sprintf(buffer+j, "%c\n", c);
   j += sprintf(buffer+j, "%d\n", i);
   j += sprintf(buffer+j, "%f\n", fp);
   printf("string:\n%s\ncharacter count = %d\n", buffer, j);
}
Output
string:
Baltimore
l
35
1.732051

character count = 24

Related information