PRINTF(3C) | Standard C Library Functions | PRINTF(3C) |
printf, fprintf, sprintf, snprintf, asprintf - print formatted output
#include <stdio.h> int printf(const char *restrict format,
/* args*/ ...);
int fprintf(FILE *restrict stream, const char *restrict format,
/* args*/ ...);
int sprintf(char *restrict s, const char *restrict format,
/* args*/ ...);
int snprintf(char *restrict s, size_t n,
const char *restrict format, /* args*/ ...);
int asprintf(char ** ret, const char *restrict format,
/* args*/ ...);
The printf() function places output on the standard output stream stdout.
The fprintf() function places output on on the named output stream stream.
The sprintf() function places output, followed by the null byte (\0), in consecutive bytes starting at s; it is the user's responsibility to ensure that enough storage is available.
The snprintf() function is identical to sprintf() with the addition of the argument n, which specifies the size of the buffer referred to by s. If n is 0, nothing is written and s can be a null pointer. Otherwise, output bytes beyond the n-1st are discarded instead of being written to the array and a null byte is written at the end of the bytes actually written into the array.
The asprintf() function is the same as the sprintf() function except that it returns, in the ret argument, a pointer to a buffer sufficiently large to hold the output string. This pointer should be passed to free(3C) to release the allocated storage when it is no longer needed. If sufficient space cannot be allocated, the asprintf() function returns -1 and sets ret to be a NULL pointer.
Each of these functions converts, formats, and prints its arguments under control of the format. The format is a character string, beginning and ending in its initial shift state, if any. The format is composed of zero or more directives: ordinary characters, which are simply copied to the output stream and conversion specifications, each of which results in the fetching of zero or more arguments. The results are undefined if there are insufficient arguments for the format. If the format is exhausted while arguments remain, the excess arguments are evaluated but are otherwise ignored.
Conversions can be applied to the nth argument after the format in the argument list, rather than to the next unused argument. In this case, the conversion specifier % (see below) is replaced by the sequence %n$, where n is a decimal integer in the range [1, NL_ARGMAX], giving the position of the argument in the argument list. This feature provides for the definition of format strings that select arguments in an order appropriate to specific languages (see the EXAMPLES section).
In format strings containing the %n$ form of conversion specifications, numbered arguments in the argument list can be referenced from the format string as many times as required.
In format strings containing the % form of conversion specifications, each argument in the argument list is used exactly once.
All forms of the printf() functions allow for the insertion of a language-dependent radix character in the output string. The radix character is defined by the program's locale (category LC_NUMERIC). In the POSIX locale, or in a locale where the radix character is not defined, the radix character defaults to a period (.).
Each conversion specification is introduced by the % character or by the character sequence %n$, after which the following appear in sequence:
If the conversion specifier is s, a standard-conforming application (see standards(7)) interprets the field width as the minimum number of bytes to be printed; an application that is not standard-conforming interprets the field width as the minimum number of columns of screen display. For an application that is not standard-conforming, %10s means if the converted value has a screen width of 7 columns, 3 spaces would be padded on the right.
If the format is %ws, then the field width should be interpreted as the minimum number of columns of screen display.
If the conversion specifier is s or S, a standard-conforming application (see standards(7)) interprets the precision as the maximum number of bytes to be written; an application that is not standard-conforming interprets the precision as the maximum number of columns of screen display. For an application that is not standard-conforming, %.5s would print only the portion of the string that would display in 5 screen columns. Only complete characters are written.
For %ws, the precision should be interpreted as the maximum number of columns of screen display. The precision takes the form of a period (.) followed by a decimal digit string; a null digit string is treated as zero. Padding specified by the precision overrides the padding specified by the field width.
A field width, or precision, or both can be indicated by an asterisk (*) . In this case, an argument of type int supplies the field width or precision. Arguments specifying field width, or precision, or both must appear in that order before the argument, if any, to be converted. A negative field width is taken as a − flag followed by a positive field width. A negative precision is taken as if the precision were omitted. In format strings containing the %n$ form of a conversion specification, a field width or precision may be indicated by the sequence *m$, where m is a decimal integer in the range [1, NL_ARGMAX] giving the position in the argument list (after the format argument) of an integer argument containing the field width or precision, for example:
printf("%1$d:%2$.*3$d:%4$.*3$d\n", hour, min, precision, sec);
The format can contain either numbered argument specifications (that is, %n$ and *m$), or unnumbered argument specifications (that is, % and *), but normally not both. The only exception to this is that %% can be mixed with the %n$ form. The results of mixing numbered and unnumbered argument specifications in a format string are undefined. When numbered argument specifications are used, specifying the Nth argument requires that all the leading arguments, from the first to the (N-1)th, are specified in the format string.
The flag characters and their meanings are:
'
−
+
space
#
0
The length modifiers and their meanings are:
hh
h
l (ell)
ll (ell-ell)
j
z
t
L
If a length modifier appears with any conversion specifier other than as specified above, the behavior is undefined.
Each conversion specifier results in fetching zero or more arguments. The results are undefined if there are insufficient arguments for the format. If the format is exhausted while arguments remain, the excess arguments are ignored.
The conversion specifiers and their meanings are:
d, i
o
u
x
X
f, F
For the f specifier, a double argument representing an infinity or NaN is converted in the style of the e conversion specifier, except that for an infinite argument, "infinity" or "Infinity" is printed when the precision is at least 8 and "inf" or "Inf" is printed otherwise.
For the F specifier, a double argument representing an infinity or NaN is converted in the SUSv3 style of the E conversion specifier, except that for an infinite argument, "INFINITY" is printed when the precision is at least 8 and or "INF" is printed otherwise.
e, E
Infinity and NaN values are handled in one of the following ways:
SUSv3
Default
g, G
A double argument representing an infinity or NaN is converted in the style of the e or E conversion specifier, except that for an infinite argument, "infinity", "INFINITY", or "Infinity" is printed when the precision is at least 8 and "inf", "INF", or "Inf" is printed otherwise.
a, A
The converted value is rounded to fit the specified output format according to the prevailing floating point rounding direction mode. If the conversion is not exact, an inexact exception is raised.
A double argument representing an infinity or NaN is converted in the SUSv3 style of an e or E conversion specifier.
c
If an l (ell) qualifier is present, the wint_t argument is converted as if by an ls conversion specification with no precision and an argument that points to a two-element array of type wchar_t, the first element of which contains the wint_t argument to the ls conversion specification and the second element contains a null wide-character.
C
wc
s
If an l (ell) qualifier is present, the argument must be a pointer to an array of type wchar_t. Wide-characters from the array are converted to characters (each as if by a call to the wcrtomb(3C) function, with the conversion state described by an mbstate_t object initialized to zero before the first wide-character is converted) up to and including a terminating null wide-character. The resulting characters are written up to (but not including) the terminating null character (byte). If no precision is specified, the array must contain a null wide-character. If a precision is specified, no more than that many characters (bytes) are written (including shift sequences, if any), and the array must contain a null wide-character if, to equal the character sequence length given by the precision, the function would need to access a wide-character one past the end of the array. In no case is a partial character written.
S
ws
p
n
%
If a conversion specification does not match one of the above forms, the behavior is undefined.
In no case does a non-existent or small field width cause truncation of a field; if the result of a conversion is wider than the field width, the field is simply expanded to contain the conversion result. Characters generated by printf() and fprintf() are printed as if the putc(3C) function had been called.
The st_ctime and st_mtime fields of the file will be marked for update between the call to a successful execution of printf() or fprintf() and the next successful completion of a call to fflush(3C) or fclose(3C) on the same stream or a call to exit(3C) or abort(3C).
The printf(), fprintf(), sprintf(), and asprintf() functions return the number of bytes transmitted (excluding the terminating null byte in the case of sprintf() and asprintf()).
The snprintf() function returns the number of bytes that would have been written to s if n had been sufficiently large (excluding the terminating null byte.) If the value of n is 0 on a call to snprintf(), s can be a null pointer and the number of bytes that would have been written if n had been sufficiently large (excluding the terminating null byte) is returned.
Each function returns a negative value if an output error was encountered.
For the conditions under which printf() and fprintf() will fail and may fail, refer to fputc(3C) or fputwc(3C).
The snprintf() function will fail if:
EOVERFLOW
The printf(), fprintf(), sprintf(), and snprintf() functions may fail if:
EILSEQ
EINVAL
The printf(), fprintf(), and asprintf() functions may fail due to an underlying malloc(3C) failure if:
EAGAIN
ENOMEM
If the application calling the printf() functions has any objects of type wint_t or wchar_t, it must also include the header <wchar.h> to have these objects defined.
It is common to use the following escape sequences built into the C language when entering format strings for the printf() functions, but these sequences are processed by the C compiler, not by the printf() function.
\a
\b
\f
\n
\r
\t
\v
In addition, the C language supports character sequences of the form
\octal-number
and
\hex-number
which translates into the character represented by the octal or hexadecimal number. For example, if ASCII representations are being used, the letter 'a' may be written as '\141' and 'Z' as '\132'. This syntax is most frequently used to represent the null character as '\0'. This is exactly equivalent to the numeric constant zero (0). Note that the octal number does not include the zero prefix as it would for a normal octal constant. To specify a hexadecimal number, omit the zero so that the prefix is an 'x' (uppercase 'X' is not allowed in this context). Support for hexadecimal sequences is an ANSI extension. See standards(7).
Example 1 To print the language-independent date and time format, the following statement could be used:
printf (format, weekday, month, day, hour, min);
For American usage, format could be a pointer to the string:
"%s, %s %d, %d:%.2d\n"
producing the message:
Sunday, July 3, 10:02
whereas for German usage, format could be a pointer to the string:
"%1$s, %3$d. %2$s, %4$d:%5$.2d\n"
producing the message:
Sonntag, 3. Juli, 10:02
Example 2 To print a date and time in the form Sunday, July 3, 10:02, where weekday and month are pointers to null-terminated strings:
printf("%s, %s %i, %d:%.2d", weekday, month, day, hour, min);
Example 3 To print pi to 5 decimal places:
printf("pi = %.5f", 4 * atan(1.0));
Example 4 The following example applies only to applications that are not standard-conforming. To print a list of names in columns which are 20 characters wide:
printf("%20s%20s%20s", lastname, firstname, middlename);
See attributes(7) for descriptions of the following attributes:
ATTRIBUTE TYPE | ATTRIBUTE VALUE |
CSI | Enabled |
Interface Stability | Committed |
MT-Level | See below. |
Standard | See below. |
All of these functions can be used safely in multithreaded applications, as long as setlocale(3C) is not being called to change the locale. The sprintf() and snprintf() functions are Async-Signal-Safe.
See standards(7) for the standards conformance of printf(), fprintf(), sprintf(), and snprintf(). The asprintf() function is modeled on the one that appears in the FreeBSD, NetBSD, and GNU C libraries.
exit(2), lseek(2), write(2), abort(3C), ecvt(3C), exit(3C), fclose(3C), fflush(3C), fputwc(3C), free(3C), malloc(3C), putc(3C), scanf(3C), setlocale(3C), stdio(3C), vprintf(3C), wcstombs(3C), wctomb(3C), attributes(7), environ(7), standards(7)
If the j length modifier is used, 32-bit applications that were compiled using c89 on releases prior to Solaris 10 will experience undefined behavior.
The snprintf() return value when n = 0 was changed in the Solaris 10 release. The change was based on the SUSv3 specification. The previous behavior was based on the initial SUSv2 specification, where snprintf() when n = 0 returns an unspecified value less than 1.
August 19, 2020 | OmniOS |