fprintf() - printf() - sprintf() — Format and Write Data
| Standards / Extensions | C or C++ | Dependencies |
|---|---|---|
POSIX.1
XPG4 XPG4.2 |
both |
Format
#include <stdio.h>
int fprintf(FILE *stream, const char *format-string, …);
int printf(const char *format-string, …);
int sprintf(char *buffer, const char *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.
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.
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.
The fprintf() and printf() functions 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, an intervening flush or reposition must occur. Between a read and a subsequent write, an intervening flush or reposition must also occur unless an EOF has been reached.
The format-string consists of ordinary characters, escape sequences, and format specifications. The ordinary characters are copied in order of their appearance. Format specifications, beginning with a percent sign (%), 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.
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, string, 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 stdout.
For example, to print a percent sign character, use %%.
The flag characters
wchar_t precision
unit.| Flag | Meaning | Default |
|---|---|---|
| - | 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. |
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 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, d, i, u, s,
or p types.
The Width of the Output
Width is a non-negative 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.
The Precision of the Output
precision is a non-negative 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.
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.
The interpretation of the precision value and the default when the precision is omitted depend upon the type, as shown in Table 2.
| Type | Meaning | Default |
|---|---|---|
|
i
d u o 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. | If precision is 0 or omitted entirely, or if the period (.) appears without a number following it, the precision is set to 1. |
|
f
e E |
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. |
|
g
G |
Precision specifies the maximum number of significant digits output. | All significant digits are output. |
|
c
|
No effect. | The character is output. |
|
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
h- A prefix with the integer types
d,i,o,u,x,X, andnthat specifies that the argument isshort intorunsigned short int. l- A prefix with
d,i,o,u,x,X, andntypes that specifies that the argument is along intorunsigned long int.The
lprefix with thectype conversion specifier indicates that the argument is a wint_t. Thelprefix with thestype conversion specifier indicates that the argument is a pointer to a wchar_t. ll- A prefix with the integer types
d,i,o,u,x,Xmeans the integer is 64 bits long. L- A prefix with
e,E,f,g, orGtypes that specifies that the argument islong double.
long double value and do
not use the L qualifier or if you pass a double value only
and use the L qualifier, errors occur.Table 3 shows the meaning of the type characters used in the precision argument.
| 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. |
| 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 -. |
| 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 g format is used only when the exponent of the value
is less than -4 or greater than precision. Trailing
zeros are truncated, and the decimal point appears only if one or
more digits follow it. |
| G | Double | Identical to the g format, except that G introduces
the exponent (where appropriate), not g. |
| D(n,p) | Decimal type argument | Fixed-point value consisting of an optional sign (+ or -); a series of one or more decimal digits possibly containing a decimal point. Note that packed decimal is supported under C only, not C++. |
| c
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 wcrtomb(). |
| s
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 wcrtomb(), 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. |
fprintf Family of Formatted Output Functions
fprintf family functions match e, E, f, g or G conversion specifiers to floating-point arguments for which they produce floating-point number substrings in the output stream. fprintf family functions have been extended to determine the floating-point format, hexadecimal floating-point or IEEE floating-point, of types e, E, f, g or G by using __isBFP().
fprintf family functions convert IEEE floating-point infinity and NaN argument values to special infinity and NaN floating-point number output sequences.
- The special output sequence for infinity values is a plus or minus
sign, then the character sequence INF followed by a white-space
character (space, tab, or newline), a NULL character (
\0) or EOF. - The special output sequence for NaN values is a plus or minus
sign, then the character sequence NANS for a signalling NaN or NANQ
for a quiet NaN, then a NaN ordinal sequence, and then a white-space
character (space, tab, or newline), a NULL character (
\0) or EOF.A NaN ordinal sequence is a left-parenthesis character, “(”, followed by a digit sequence representing an integer n, where 1 <= n <= INT_MAX-1, followed by a right-parenthesis character, “)”. The integer value, n, is determined by the fraction bits of the NaN argument value as follows:
- For a signalling NaN value, NaN fraction bits are reversed (left to right) to produce bits (right to left) of an even integer value, 2*n. Then formatted output functions produce a (signalling) NaN ordinal sequence corresponding to the integer value 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. Then formatted output functions produce a (quiet) NaN ordinal sequence corresponding to the integer value n.
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/VM 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.
The sprintf() function is available to C applications in a stand-alone Systems Programming Environment.
Returned Value
The fprintf(), printf(), and sprintf() functions return the number of characters output, or a negative value if an output error occurs. The ending null character is not counted.
Examples
CBC3BF30
/* CBC3BF30
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);
}
CBC3BF30 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
CBC3BF31
/* CBC3BF31
The following example illustrates the use of printf() to print
fixed-point decimal data types.
*/
#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);
}
CBC3BF31 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
CBC3BF32
/* CBC3BF32
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);
}
CBC3BF32 Output
string:
baltimore
l
35
1.732051
character count = 24
Related Information
- For information about locales and character sets, see z/OS: XL C/C++ Programming Guide.
- locale.h
- stdio.h
- wchar.h
- fscanf() - scanf() - sscanf() — Read and Format Data
- localeconv() — Query Numeric Conventions
- setlocale() — Set Locale
- wcrtomb() — Convert a Wide Character to a Multibyte Character
