printf(3)
๐ NAME ๐
okay so bestie, welcome to the printf(3) family group chat โ this is the Library Functions Manual page, and it's a lot, but we're gonna get through it together ๐ซถ
printf, fprintf, dprintf, vprintf, vfprintf, vdprintf, โ formatted output conversion โจ
(also, lowkey the manual's name is just printf(3), that's the whole title, slay)
๐ LIBRARY
Standard C library (libc, -lc)
โจ SYNOPSIS โจ
#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 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);
๐ง Feature Test Macro Requirements for glibc (see feature_test_macros(7)):
dprintf(),vdprintf():- Since glibc 2.10:
_POSIX_C_SOURCE >= 200809L
- Before glibc 2.10:
_GNU_SOURCE
- Since glibc 2.10:
๐ธ DESCRIPTION ๐ธ
so like. the functions in the printf() family produce output according to a format, as described down below ๐ and honestly it's giving "I contain multitudes."
printf() and vprintf() write output to stdout, the standard output stream. fprintf() and vfprintf() write output to the given output stream. classic.
dprintf() is the same as fprintf() except that it outputs to a file descriptor, fd, instead of to a stdio(3) stream. no stream, just raw fd energy ๐
vprintf(), vfprintf(), vdprintf() are equivalent to printf(), fprintf(), dprintf(), respectively, except that they're called with a va_list instead of a variable number of arguments. important: these functions do not call the va_end macro. and 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 โจ
๐ 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 overall syntax of a conversion specification is:
%[argument$][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. no skipping, bestie ๐
โโ๏ธ
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 ๐
๐ Flag characters
The character % is followed by zero or more of the following flags:
#โ The value should be converted to an "alternate form". Foroconversions, the first character of the output string is made zero (by prefixing a0if it was not zero already). ForxandXconversions, a nonzero result has the string"0x"(or"0X"forXconversions) prepended to it. Fora,A,e,E,f,F,g, andGconversions, the result will always contain a decimal point, even if no digits follow it (normally, a decimal point appears in the results of those conversions only if a digit follows). ForgandGconversions, trailing zeros are not removed from the result as they would otherwise be. Form, iferrnocontains a valid error code, the output ofstrerrorname_np(errno)is printed; otherwise, the value stored inerrnois printed as a decimal number. For other conversions, the result is undefined ๐0โ The value should be zero padded. Ford,i,o,u,x,X,a,A,e,E,f,F,g, andGconversions, the converted value is padded on the left with zeros rather than blanks. If the0and-flags both appear, the0flag is ignored. If a precision is given with an integer conversion (d,i,o,u,x, andX), the0flag is ignored. For other conversions, the behavior is undefined ๐-โ The converted value is to be left adjusted on the field boundary. (The default is right justification.) The converted value is padded on the right with blanks, rather than on the left with blanks or zeros. A-overrides a0if both are given.' '(a space) โ A blank should be left before a positive number (or empty string) produced by a signed conversion.+โ A sign (+or-) should always be placed before a number produced by a signed conversion. By default, a sign is used only for negative numbers. A+overrides a space if both are used.
The five flag characters above are defined in the C99 standard. POSIX specifies one further flag character โจ
'โ For decimal conversion (i,d,u,f,F,g,G) the output is to be grouped with thousands' grouping characters as a non-monetary quantity. Misleadingly, this isn't necessarily every thousand: for example Karbi ("mjw_IN"), groups its digits into 3 once, then 2 repeatedly ๐ซ Comparelocale(7)grouping andthousands_sep, contrast withmon_grouping/mon_thousands_sepandstrfmon(3). This is a no-op in the default"C"locale.
glibc 2.2 adds one further flag character ๐
Iโ For decimal integer conversion (i,d,u) the output uses the locale's alternative output digits, if any. For example, since glibc 2.2.3 this will give Arabic-Indic digits in the Persian ("fa_IR") locale ๐
๐ 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 ๐ช no data lost, periodt.
๐ 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, andXconversions, - the number of digits to appear after the radix character for
a,A,e,E,f, andFconversions, - the maximum number of significant digits for
gandGconversions, - or the maximum number of characters to be printed from a string for
sandSconversions ๐
๐งฌ Length modifier
Here, "integer conversion" stands for d, i, o, u, x, or X conversion.
hhโ A following integer conversion corresponds to asigned charorunsigned charargument, or a followingnconversion corresponds to a pointer to asigned charargument.hโ A following integer conversion corresponds to ashortorunsigned shortargument, or a followingnconversion corresponds to a pointer to ashortargument.l(ell) โ A following integer conversion corresponds to alongorunsigned longargument, or a followingnconversion corresponds to a pointer to alongargument, or a followingcconversion corresponds to awint_targument, or a followingsconversion corresponds to a pointer towchar_targument. On a followinga,A,e,E,f,F,g, orGconversion, this length modifier is ignored (C99; not in SUSv2).ll(ell-ell) โ A following integer conversion corresponds to along longorunsigned long longargument, or a followingnconversion corresponds to a pointer to along longargument.qโ A synonym forll. This is a nonstandard extension, derived from BSD; avoid its use in new code ๐Lโ A followinga,A,e,E,f,F,g, orGconversion corresponds to along doubleargument. (C99 allows%LF, but SUSv2 does not.)jโ A following integer conversion corresponds to anintmax_toruintmax_targument, or a followingnconversion corresponds to a pointer to anintmax_targument.wNโ A following integer conversion corresponds to an integer of a width of N bits (C23) โญzโ A following integer conversion corresponds to asize_torssize_targument, or a followingnconversion corresponds to a pointer to asize_targument.Zโ A nonstandard synonym forzthat predates the appearance ofz. Do not use in new code ๐ธtโ okay so atbefore an integer conversion means the arg is aptrdiff_t, and if it's sitting in front of annconversion then you're pointing at aptrdiff_t. That's the whole deal. โจ
SUSv3 specifies literally all of the above โ except the ones we explicitly called out as nonstandard extensions, bestie, those are the wild ones. SUSv2 was way more limited: it only knew 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). That's it. She was doing her best. ๐
As a nonstandard extension (key words, it's giving not-portable), the GNU implementations treat ll and L as synonyms, so you can literally write llg (as a synonym for the standards-compliant Lg) and Ld (as a synonym for the standards compliant lld). Such usage is nonportable. ๐จ Like, it works on GNU, don't go shipping it everywhere and acting surprised.
โจ Conversion specifiers โจ
A character that specifies the type of conversion to be applied. The conversion specifiers and their meanings are, bestie, a whole vibe:
d,iโ theintargument gets converted to signed decimal notation. The precision, if any, gives the minimum number of digits that must appear; if the converted value needs fewer digits, it gets padded on the left with zeros. Default precision is1. And when0is printed with an explicit precision0, the output is empty. Nothing. Silence. Iconic. ๐ซถo,u,x,Xโ theunsigned intargument gets converted to unsigned octal (o), unsigned decimal (u), or unsigned hexadecimal (xandX) notation. The lettersabcdefare used forxconversions; the lettersABCDEFare used forXconversions. The precision, if any, gives the minimum number of digits that must appear; if the converted value needs fewer digits, it gets padded on the left with zeros. Default precision is1. When0is printed with an explicit precision0, the output is empty. Same energy as above, different base. ๐ขe,Eโ thedoubleargument is rounded and converted in the style[-]d.dddeยฑddwhere there's one digit (which is nonzero if the argument is nonzero) before the decimal-point character, and the number of digits after it is equal to the precision; if the precision is missing, it's taken as6; if the precision is zero, no decimal-point character appears. AnEconversion uses the letterE(rather thane) to introduce the exponent. The exponent always contains at least two digits; if the value is zero, the exponent is00. ๐f,Fโ thedoubleargument is rounded and converted to decimal notation in the style[-]ddd.ddd, where the number of digits after the decimal-point character is equal to the precision specification. If the precision is missing, it's taken as6; if the precision is explicitly zero, no decimal-point character appears. If a decimal point does appear, at least one digit appears before it. Validating.
(Okay so: SUSv2 does not know about F and says that character string representations for infinity and NaN may be made available. SUSv3 adds a specification for F. The C99 standard specifies "[-]inf" or "[-]infinity" for infinity, and a string starting with "nan" for NaN, in the case of f conversion, and "[-]INF" or "[-]INFINITY" or "NAN" in the case of F conversion. So yes, she yells it in caps. ๐ฃ๏ธ)
g,Gโ thedoubleargument gets converted in stylefore(orForEforGconversions). The precision specifies the number of significant digits. If the precision is missing,6digits are given; if the precision is zero, it's treated as1. Styleeis used if the exponent from its conversion is less than-4or greater than or equal to the precision. Trailing zeros are removed from the fractional part of the result; a decimal point appears only if it's followed by at least one digit. She's efficient, she doesn't keep the baggage. โ๏ธa,Aโ (C99; not inSUSv2, but added inSUSv3.) Foraconversion, thedoubleargument is converted to hexadecimal notation (using the lettersabcdef) in the style[-]0xh.hhhhpยฑd; forAconversion the prefix0X, the lettersABCDEF, and the exponent separatorPis used. There is one hexadecimal digit before the radix point, and the number of digits after it is equal to the precision. The default precision suffices for an exact representation of the value if an exact representation in base 2 exists and otherwise is sufficiently large to distinguish values of typedouble. The digit before the radix point is unspecified for nonnormalized numbers, and nonzero but otherwise unspecified for normalized numbers. The exponent,d, is the appropriate exponent of 2 expressed as a decimal integer; it always contains at least one digit; if the value is zero, the exponent is0. That's a lot of words but she ate. ๐ฅcโ if nolmodifier is present, theintargument is converted to anunsigned char, and the resulting character is written. If anlmodifier is present, thewint_t(wide character) argument is converted to a multibyte sequence by a call to thewcrtomb(3)function, with a conversion state starting in the initial state, and the resulting multibyte string is written. Wide girl summer. ๐sโ if nolmodifier is present: theconst char *argument is expected to be a pointer to an array of character type (pointer to a string). Characters from the array are written up to (but not including) a terminating null byte ('\0'); if a precision is specified, no more than the number specified are written. If a precision is given, no null byte need be present; if the precision is not specified, or is greater than the size of the array, the array must contain a terminating null byte.
If an l modifier is present: the const wchar_t * argument is expected to be a pointer to an array of wide characters. Wide characters from the array are converted to multibyte characters (each by a call to the wcrtomb(3) function, with a conversion state starting in the initial state before the first wide character), up to and including a terminating null wide character. The resulting multibyte characters are written up to (but not including) the terminating null byte. If a precision is specified, no more bytes than the number specified are written, but no partial multibyte characters are written. Note that the precision determines the number of bytes written, not the number of wide characters or screen positions. The array must contain a terminating null wide character, unless a precision is given and it's so small that the number of bytes written exceeds it before the end of the array is reached. ๐ฆ
Cโ (Not in C99 or C11, but inSUSv2,SUSv3, andSUSv4.) Synonym forlc. Don't use. ๐ซ That's it, that's the review.Sโ (Not in C99 or C11, but inSUSv2,SUSv3, andSUSv4.) Synonym forls. Don't use. ๐ซ Same energy, equally don't.pโ thevoid *pointer argument is printed in hexadecimal (as if by%#xor%#lx). Pointers, but make it โจhexโจ.nโ the number of characters written so far is stored into the integer pointed to by the corresponding argument. That argument shall be anint *, or variant whose size matches the (optionally) supplied integer length modifier. No argument is converted. (This specifier is not supported by the bionic C library.) The behavior is undefined if the conversion specification includes any flags, a field width, or a precision. > Girl. Do not. This one is the villain of the entire manpage, and it's the reasonprintf(foo)is dangerous (see BUGS, we'll get there ๐).mโ (glibc extension; supported by uClibc and musl, and on Android from API level 29.) Print output ofstrerror(errno)(orstrerrorname_np(errno)in the alternate form). No argument is required. Free error string, no arg needed, she's generous. ๐%โ a%is written. No argument is converted. The complete conversion specification is%%. Escaping herself, love that for her. ๐
๐ซ RETURN VALUE ๐ซ
Upon successful return, these functions return the number of bytes printed (excluding the null byte used to end output to strings). So, the count, not the vibe. ๐
On error, a negative value is returned, and errno is set to indicate the error. Rude, but informative.
๐ญ ERRORS ๐ญ
See write(2) and putwc(3). In addition, the following error may occur:
EOVERFLOWโ the value to be returned is greater thanINT_MAX. Bestie you did too much. She can't count that high.
The dprintf() function may fail additionally if:
EBADFโ thefdargument is not a valid file descriptor. That's not a real fd, babe. ๐
๐ซถ ATTRIBUTES ๐ซถ
For an explanation of the terms used in this section, see attributes(7).
printf(),fprintf(),vprintf(),vfprintf()โ Thread safety:MT-Safe locale. Slay, she's thread safe. (Well, locale thread safe. iykyk.)
๐ STANDARDS ๐
fprintf(),printf(),vprintf(),vfprintf()โ C11, POSIX.1-2008.dprintf(),vdprintf()โ GNU, POSIX.1-2008.
๐ธ HISTORY ๐ธ
fprintf(),printf(),vprintf(),vfprintf()โ C89, POSIX.1-2001.dprintf(),vdprintf()โ GNU, POSIX.1-2008.
Issue 4 of the X/Open Portability Guide (SUSv1, 1994) adds '.
glibc 2.1 adds length modifiers hh, j, t, and z and conversion characters a and A. The glow up. โจ
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. New lore dropped in 2.35. ๐
๐ BUGS ๐
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. ๐๐๐
No fr, this is the real one. Keep your user input out of the format string. Not me watching people pass untrusted strings straight into printf. ๐จ
โจ EXAMPLES โจ
Okay bestie, time for the fun part โ actually using this thing. ๐
Wanna print Pi to five decimal places? Say less:
#include <math.h>
#include <stdio.h>
fprintf(stdout, "pi = %.5f\n", 4 * atan(1.0));
Look at that. Five decimals. Iconic behaviour, no notes. ๐
Now say you want a date and time looking like "Sunday, July 3, 10:02", where weekday and month are pointers to strings. Boom:
#include <stdio.h>
fprintf(stdout, "%s, %s %d, %.2d:%.2d\n",
weekday, month, day, hour, min);
Cute, right? Month name first, day second โ very American of it. ๐บ๐ธ
Here's the plot twist though: so many countries do day-month-year, because honestly why would you do it any other way. So an internationalized version has to be able to print the arguments in an order that the format itself decides. Like this:
#include <stdio.h>
fprintf(stdout, format,
weekday, month, day, hour, min);
where format depends on the locale, and โ this is the juicy bit โ it may permute the arguments. Rearrange them. Shuffle them. The format is in charge. ๐ค
So if format has the value:
"%1$s, %3$d. %2$s, %4$d:%5$.2d\n"
then one might obtain:
"Sonntag, 3. Juli, 10:02"
SEEE. The position arguments (%1$s, %3$d, %2$sโฆ) let you pull the args back out of order, so German gets its day-first moment. Lรคnder representation, we love to see it. ๐ฉ๐ชโจ
๐ SEE ALSO ๐
Your reading list, bestie โ go be nosy:
printf(1)asprintf(3)puts(3)scanf(3)setlocale(3)snprintf(3)strfromd(3)wcrtomb(3)wprintf(3)locale(5)
And that's a wrap on printf(3)! ๐ซถ This little masterpiece is from Linux man-pages 6.20, dated 2026-02-16 โ go forth and format responsibly, my love. ๐โจ
๐ฆ where this page comes from
- arch rolling: man-pages 6.20-1 ยท BSD-2-Clause AND BSD-3-Clause AND BSD-4.3TAHOE AND BSD-4-Clause-UC AND GPL-1.0-or-later AND GPL-2.0-only AND GPL-2.0-or-later AND GPL-3.0-or-later AND LGPL-3.0-linking-exception AND LGPL-3.0-or-later AND LicenseRef-Public-Domain AND LicenseRef-UltraPermissive AND Linux-man-pages-1-para AND Linux-man-pages-copyleft AND Linux-man-pages-copyleft-2-para AND Linux-man-pages-copyleft-var AND MIT AND Spencer-94
- nixpkgs unstable: man-pages 6.20
- ๐ the page's license: GPL-2.0-or-later
- Copyright 1999, Andries E. Brouwer <aeb@cwi.nl>
- ๐ girlified by deepseek-ai/DeepSeek-V4.1-Flash on : a language model's rewrite of the original, under its terms