printf(3P, 3p) | print formatted output |
printf, dprintf, fprintf, snprintf, sprintf, vdprintf, vfprintf, vprintf, vsnprintf, vsprintf(3) | formatted output conversion |
fprintf, dprintf, printf, snprintf, sprintf(3P, 3p) | print formatted output |
printf(3) | Library Functions Manual | printf(3) |
printf, fprintf, dprintf, sprintf, snprintf, vprintf, vfprintf, vdprintf, vsprintf, vsnprintf - formatted output conversion
Standard C library (libc, -lc)
#include <stdio.h>
int printf(const char *restrict format, ...); int fprintf(FILE *restrict stream, const char *restrict format, ...); int dprintf(int fd, const char *restrict format, ...); int sprintf(char *restrict str, const char *restrict format, ...); int snprintf(char str[restrict .size], size_t size, const char *restrict format, ...);
int vprintf(const char *restrict format, va_list ap); int vfprintf(FILE *restrict stream, const char *restrict format, va_list ap); int vdprintf(int fd, const char *restrict format, va_list ap); int vsprintf(char *restrict str, const char *restrict format, va_list ap); int vsnprintf(char str[restrict .size], size_t size, const char *restrict format, va_list ap);
snprintf(), vsnprintf():
_XOPEN_SOURCE >= 500 || _ISOC99_SOURCE
|| /* glibc <= 2.19: */ _BSD_SOURCE
dprintf(), vdprintf():
Since glibc 2.10:
_POSIX_C_SOURCE >= 200809L
Before glibc 2.10:
_GNU_SOURCE
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(3) 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.
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 overall syntax of a conversion specification is:
%[$][flags][width][.precision][length modifier]conversion
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,
printf("%'.2f", 1234567.89);
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 character % is followed by zero or more of the following flags:
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.
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.
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.
Here, "integer conversion" stands for d, i, o, u, x, or X conversion.
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.
A character that specifies the type of conversion to be applied. The conversion specifiers and their meanings are:
Upon successful return, these functions return the number of characters printed (excluding the null byte used to end output to strings).
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.
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 |
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.
glibc 2.35 gives a meaning to the alternate form (#) of the m conversion specifier, that is %#m.
Some programs imprudently rely on code such as the following
sprintf(buf, "%s some further text", buf);
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 2.1. Until glibc 2.0.6, they would return -1 when the output was truncated.
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)).
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.
To print Pi to five decimal places:
#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",
weekday, month, day, hour, min);
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,
weekday, month, day, hour, min);
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, ...) {
int n = 0;
size_t size = 0;
char *p = NULL;
va_list ap;
/* Determine required size. */
va_start(ap, fmt);
n = vsnprintf(p, size, fmt, ap);
va_end(ap);
if (n < 0)
return NULL;
size = (size_t) n + 1; /* One extra byte for '\0' */
p = malloc(size);
if (p == NULL)
return NULL;
va_start(ap, fmt);
n = vsnprintf(p, size, fmt, ap);
va_end(ap);
if (n < 0) {
free(p);
return NULL;
}
return p; }
If truncation occurs in glibc versions prior to glibc 2.0.6, this is treated as an error instead of being handled gracefully.
printf(1), asprintf(3), puts(3), scanf(3), setlocale(3), strfromd(3), wcrtomb(3), wprintf(3), locale(5)
2023-07-20 | Linux man-pages 6.05.01 |