printf (3) - Linux Man Pages
printf: formatted output conversion
NAME
printf, fprintf, dprintf, sprintf, snprintf, vprintf, vfprintf, vdprintf, vsprintf, vsnprintf - formatted output conversion
SYNOPSIS
#include <stdio.h> int printf(const char *format, ...); int fprintf(FILE *stream, const char *format, ...); int dprintf(int fd, const char *format, ...); int sprintf(char *str, const char *format, ...); int snprintf(char *str, size_t size, const char *format, ...); #include <stdarg.h> int vprintf(const char *format, va_list ap); int vfprintf(FILE *stream, const char *format, va_list ap); int vdprintf(int fd, const char *format, va_list ap); int vsprintf(char *str, const char *format, va_list ap); int vsnprintf(char *str, size_t size, const char *format, va_list ap);
Feature Test Macro Requirements for glibc (see feature_test_macros(7)):
snprintf(), vsnprintf():
-
_XOPEN_SOURCE >= 500 || _ISOC99_SOURCE ||
|| /* Glibc versions <= 2.19: */ _BSD_SOURCE
dprintf(), vdprintf():
-
- Since glibc 2.10:
- _POSIX_C_SOURCE >= 200809L
- Before glibc 2.10:
- _GNU_SOURCE
DESCRIPTION
The functions in the printf() family produce output according to a format as described below. The functions printf() and vprintf() write output to stdout, the standard output stream; fprintf() and vfprintf() write output to the given output stream; sprintf(), snprintf(), vsprintf() and vsnprintf() write to the character string str.The function dprintf() is the same as fprintf() except that it outputs to a file descriptor, fd, instead of to a stdio stream.
The functions snprintf() and vsnprintf() write at most size bytes (including the terminating null byte ('\0')) to str.
The functions vprintf(), vfprintf(), vdprintf(), vsprintf(), vsnprintf() are equivalent to the functions printf(), fprintf(), dprintf(), sprintf(), snprintf(), respectively, except that they are called with a va_list instead of a variable number of arguments. These functions do not call the va_end macro. Because they invoke the va_arg macro, the value of ap is undefined after the call. See stdarg(3).
All of these functions write the output under the control of a format string that specifies how subsequent arguments (or arguments accessed via the variable-length argument facilities of stdarg(3)) are converted for output.
C99 and POSIX.1-2001 specify that the results are undefined if a call to sprintf(), snprintf(), vsprintf(), or vsnprintf() would cause copying to take place between objects that overlap (e.g., if the target string array and one of the supplied input arguments refer to the same buffer). See NOTES.
Format of the format string
The format string is a character string, beginning and ending in its initial shift state, if any. The format string is composed of zero or more directives: ordinary characters (not %), which are copied unchanged to the output stream; and conversion specifications, each of which results in fetching zero or more subsequent arguments. Each conversion specification is introduced by the character %, and ends with a conversion specifier. In between there may be (in this order) zero or more flags, an optional minimum field width, an optional precision and an optional length modifier.The arguments must correspond properly (after type promotion) with the conversion specifier. By default, the arguments are used in the order given, where each '*' (see Field width and Precision below) and each conversion specifier asks for the next argument (and it is an error if insufficiently many arguments are given). One can also specify explicitly which argument is taken, at each place where an argument is required, by writing "%m$" instead of '%' and "*m$" instead of '*', where the decimal integer m denotes the position in the argument list of the desired argument, indexed starting from 1. Thus,
printf("%*d", width, num);
and
printf("%2$*1$d", width, num);
are equivalent. The second style allows repeated references to the same argument. The C99 standard does not include the style using '$', which comes from the Single UNIX Specification. If the style using '$' is used, it must be used throughout for all conversions taking an argument and all width and precision arguments, but it may be mixed with "%%" formats, which do not consume an argument. There may be no gaps in the numbers of arguments specified using '$'; for example, if arguments 1 and 3 are specified, argument 2 must also be specified somewhere in the format string.
For some numeric conversions a radix character ("decimal point") or thousands' grouping character is used. The actual character used depends on the LC_NUMERIC part of the locale. (See setlocale(3).) The POSIX locale uses '.' as radix character, and does not have a grouping character. Thus,
results in "1234567.89" in the POSIX locale, in "1234567,89" in the
nl_NL locale, and in "1.234.567,89" in the da_DK locale.
The five flag characters above are defined in the C99 standard.
The Single UNIX Specification specifies one further flag character.
glibc 2.2 adds one further flag character.
SUSv3 specifies all of the above,
except for those modifiers explicitly noted as being nonstandard extensions.
SUSv2 specified only the length modifiers
h
(in
hd,
hi,
ho,
hx,
hX,
hn)
and
l
(in
ld,
li,
lo,
lx,
lX,
ln,
lc,
ls)
and
L
(in
Le,
LE,
Lf,
Lg,
LG).
As a nonstandard extension, the GNU implementations treats
ll
and
L
as synonyms, so that one can, for example, write
llg
(as a synonym for the standards-compliant
Lg)
and
Ld
(as a synonym for the standards compliant
lld).
Such usage is nonportable.
The functions
snprintf()
and
vsnprintf()
do not write more than
size
bytes (including the terminating null byte ('\0')).
If the output was truncated due to this limit, then the return value
is the number of characters (excluding the terminating null byte)
which would have been written to the final string if enough space
had been available.
Thus, a return value of
size
or more means that the output was truncated.
(See also below under NOTES.)
If an output error is encountered, a negative value is returned.
snprintf(),
vsnprintf():
POSIX.1-2001, POSIX.1-2008, C99.
The
dprintf()
and
vdprintf()
functions were originally GNU extensions that were later standardized
in POSIX.1-2008.
Concerning the return value of
snprintf(),
SUSv2 and C99 contradict each other: when
snprintf()
is called with
size=0
then SUSv2 stipulates an unspecified return value less than 1,
while C99 allows
str
to be NULL in this case, and gives the return value (as always)
as the number of characters that would have been written in case
the output string has been large enough.
POSIX.1-2001 and later align their specification of
snprintf()
with C99.
glibc 2.1 adds length modifiers hh, j, t, and z
and conversion characters a and A.
glibc 2.2 adds the conversion character F with C99 semantics,
and the flag character I.
to append text to
buf.
However, the standards explicitly note that the results are undefined
if source and destination buffers overlap when calling
sprintf(),
snprintf(),
vsprintf(),
and
vsnprintf().
Depending on the version of
gcc(1)
used, and the compiler options employed, calls such as the above will
not
produce the expected results.
The glibc implementation of the functions
snprintf()
and
vsnprintf()
conforms to the C99 standard, that is, behaves as described above,
since glibc version 2.1.
Until glibc 2.0.6, they would return -1
when the output was truncated.
Code such as
printf(foo);
often indicates a bug, since
foo
may contain a % character.
If
foo
comes from untrusted user input, it may contain %n, causing the
printf()
call to write to memory and creating a security hole.
#include <math.h>
#include <stdio.h>
fprintf(stdout, "pi = %.5f\n", 4 * atan(1.0));
To print a date and time in the form "Sunday, July 3, 10:02",
where
weekday
and
month
are pointers to strings:
#include <stdio.h>
fprintf(stdout, "%s, %s %d, %.2d:%.2d\n",
Many countries use the day-month-year order.
Hence, an internationalized version must be able to print
the arguments in an order specified by the format:
#include <stdio.h>
fprintf(stdout, format,
where
format
depends on locale, and may permute the arguments.
With the value:
"%1$s, %3$d. %2$s, %4$d:%5$.2d\n"
one might obtain "Sonntag, 3. Juli, 10:02".
To allocate a sufficiently large string and print into it
(code correct for both glibc 2.0 and glibc 2.1):
#include <stdio.h>
#include <stdlib.h>
#include <stdarg.h>
char *
make_message(const char *fmt, ...)
{
If truncation occurs in glibc versions prior to 2.0.6, this is treated as an
error instead of being handled gracefully.
Flag characters
The character % is followed by zero or more of the following flags:
Field width
An optional decimal digit string (with nonzero first digit) specifying
a minimum field width.
If the converted value has fewer characters
than the field width, it will be padded with spaces on the left
(or right, if the left-adjustment flag has been given).
Instead of a decimal digit string one may write "*" or "*m$"
(for some decimal integer m) to specify that the field width
is given in the next argument, or in the m-th argument, respectively,
which must be of type
int.
A negative field width is taken as a '-' flag followed by a
positive field width.
In no case does a nonexistent or small field width cause truncation of a
field; if the result of a conversion is wider than the field width, the
field is expanded to contain the conversion result.
Precision
An optional precision, in the form of a period ('.') followed by an
optional decimal digit string.
Instead of a decimal digit string one may write "*" or "*m$"
(for some decimal integer m) to specify that the precision
is given in the next argument, or in the m-th argument, respectively,
which must be of type
int.
If the precision is given as just '.', the precision is taken to
be zero.
A negative precision is taken as if the precision were omitted.
This gives the minimum number of digits to appear for
d,
i,
o,
u,
x,
and
X
conversions, the number of digits to appear after the radix character for
a,
A,
e,
E,
f,
and
F
conversions, the maximum number of significant digits for
g
and
G
conversions, or the maximum number of characters to be printed from a
string for
s
and
S
conversions.
Length modifier
Here, "integer conversion" stands for
d,
i,
o,
u,
x,
or
X
conversion.
Conversion specifiers
A character that specifies the type of conversion to be applied.
The conversion specifiers and their meanings are:
RETURN VALUE
Upon successful return, these functions return the number of characters
printed (excluding the null byte used to end output to strings).
ATTRIBUTES
For an explanation of the terms used in this section, see
attributes(7).
Interface Attribute Value
printf(),
fprintf(),
sprintf(),
snprintf(),
vprintf(),
vfprintf(),
vsprintf(),
vsnprintf()
Thread safety MT-Safe locale CONFORMING TO
fprintf(),
printf(),
sprintf(),
vprintf(),
vfprintf(),
vsprintf():
POSIX.1-2001, POSIX.1-2008, C89, C99.
NOTES
Some programs imprudently rely on code such as the following
BUGS
Because
sprintf()
and
vsprintf()
assume an arbitrarily long string, callers must be careful not to overflow
the actual space; this is often impossible to assure.
Note that the length
of the strings produced is locale-dependent and difficult to predict.
Use
snprintf()
and
vsnprintf()
instead (or
asprintf(3)
and
vasprintf(3)).
EXAMPLE
To print
Pi
to five decimal places:
COLOPHON
This page is part of release 5.05 of the Linux
man-pages
project.
A description of the project,
information about reporting bugs,
and the latest version of this page,
can be found at
https://www.kernel.org/doc/man-pages/.
SEE ALSO
printf(1),
asprintf(3),
puts(3),
scanf(3),
setlocale(3),
strfromd(3),
wcrtomb(3),
wprintf(3),
locale(5)