{{Short description|C function to format and output text}} {{More citations needed|date=February 2015}} {{Use dmy dates|date=January 2021}} {{Use American English|date=February 2025}} {{lowercase title|title=printf}} 350px|thumb|alt=Diagram illustrating syntax of printf function. The first argument to the function is a template string, which may contain format specifiers, which are introduced with the percent sign (%) character. Format specifiers instruct printf how to interpret and output values given in the corresponding arguments which follow the format string. printf replaces the format specifiers with the accordingly-interpreted contents of the remaining arguments, and outputs the result.|An example call to the printf function

'''{{mono|printf}}''' is a C standard library function and is also a Linux terminal ''(shell)'' command that formats text and writes it to standard output. The function accepts a format C-string argument and a variable number of value arguments that the function serializes per the format string. Mismatch between the format specifiers and count and type of values results in undefined behavior, and the program might crash or vulnerabilities may arise.

The format string is encoded as a template language consisting of verbatim text and ''format specifiers'' that each specify how to serialize a value. As the format string is processed left-to-right, a subsequent value is used for each format specifier found. A format specifier starts with a {{code|%}} character and has one or more following characters that specify how to serialize a value.

The standard library provides other, similar functions that form a family of ''printf-like'' functions. The functions share the same formatting capabilities but provide different behavior such as output to a different destination or safety measures that limit exposure to vulnerabilities. Functions of the printf-family have been implemented in other computer programming contexts (i.e., programming languages) with the same or similar syntax and semantics.

The {{mono|scanf()}} C standard library function complements printf by providing formatted input (a.k.a. lexing, a.k.a. parsing) via a similar format string syntax.

The name, ''{{mono|printf}}'', is short for ''print formatted'' where ''print'' refers to output to a printer although the function is not limited to printer output. Today, print refers to output to any text-based environment such as a terminal or a file.

==History== ===1950s: Fortran=== Early programming languages like Fortran used special statements with different syntax from other calculations to build formatting descriptions.<ref name="Sayre_1956">{{cite book |title=The FORTRAN Automatic Coding System for the IBM 704 EDPM: Programmer's Reference Manual |publisher=Applied Science Division and Programming Research Department, International Business Machines Corporation |location=New York, USA |date=October 15, 1956 |editor-first=David |editor-last=Sayre |editor-link=David Sayre |author-first1=John Warner |author-last1=Backus |author-link1=John Warner Backus |author-first2=R. J. |author-last2=Beeber |author-first3=Sheldon F. |author-last3=Best |author-first4=Richard |author-last4=Goldberg |author-first5=Harlan L. |author-last5=Herrick |author-first6=R. A. |author-last6=Hughes |author-first7=L. B. |author-last7=Mitchell |author-first8=Robert A. |author-last8=Nelson |author-first9=Roy |author-last9=Nutt |author-link9=Roy Nutt |author-first10=David |author-last10=Sayre |author-link10=David Sayre |author-first11=Peter B. |author-last11=Sheridan |author-first12=Harold |author-last12=Stern |author-first13=Irving |author-last13=Ziller |pages=26–30 |url=http://archive.computerhistory.org/resources/text/Fortran/102649787.05.01.acc.pdf |access-date=July 4, 2022 |url-status=live |archive-url=https://web.archive.org/web/20220704193549/http://archive.computerhistory.org/resources/text/Fortran/102649787.05.01.acc.pdf |archive-date=July 4, 2022}} (2+51+1 pages)</ref> In this example, the format is specified on line {{samp|601}}, and the {{code|PRINT|fortran}}{{efn|According to the 1956 Fortran manual{{r|Sayre_1956}}, the {{code|PRINT|fortran}} command prints on the attached printer. The manual also introduces the command {{code|WRITE OUTPUT TAPE|fortran}} that also uses the {{code|FORMAT|fortran}} statement to write on a tape unit.}} command refers to it by line number: <syntaxhighlight lang="fortranfixed"> PRINT 601, IA, IB, AREA 601 FORMAT (4H A= ,I5,5H B= ,I5,8H AREA= ,F10.2, 13H SQUARE UNITS) </syntaxhighlight>

Hereby: * {{code|4H|fortran}} indicates a string of 4 characters <code>" A= "</code> ({{code|H}} means Hollerith Field); * {{code|I5|fortran}} indicates an integer field of width 5; * {{code|F10.2|fortran}} indicates a floating-point field of width 10 with 2 digits after the decimal point.

An output with input arguments {{code|100}}, {{code|200}}, and {{code|1500.25}} might look like this: <syntaxhighlight lang="output"> A= 100 B= 200 AREA= 1500.25 SQUARE UNITS </syntaxhighlight>

===1960s: BCPL and ALGOL 68=== <!-- Question: did the BCPL writef library routine already appear in 1967, or later only? --> In 1967, BCPL appeared.<ref>{{cite web |url=http://www.cl.cam.ac.uk/users/mr/BCPL.html |title=BCPL |website=cl.cam.ac.uk |access-date=19 March 2018}}</ref> Its library included the {{code|writef}} routine which looked like any other function call.<ref>{{cite book |last1=Richards |first1=Martin |last2=Whitby-Strevens |first2=Colin |date=1979 |title=BCPL - the language and its compiler |publisher=Cambridge University Press |page=[https://archive.org/details/richards1979bcpl/page/n57 50] |url=https://archive.org/details/richards1979bcpl}}</ref> An example application looks like this: <syntaxhighlight lang="text"> WRITEF("%I2-QUEENS PROBLEM HAS %I5 SOLUTIONS*N", NUMQUEENS, COUNT) </syntaxhighlight>

Hereby: * {{code|%I2}} indicates an integer of width 2 (the order of the format specification's field width and type is reversed compared to C's {{code|printf}}); * {{code|%I5}} indicates an integer of width 5; * {{code|*N}} is a BCPL ''language'' escape sequence representing a newline character (for which C uses the escape sequence {{code|\n}}).

ALGOL 68 also had a function api, but used special syntax for the format: <syntaxhighlight lang="cpp"> printf(($"Color "g", number1 "6d,", number2 "4zd,", hex "16r2d,", float "-d.2d,", unsigned value"-3d"."l$, "red", 123456, 89, BIN 255, 3.14, 250)); </syntaxhighlight>

Using normal function syntax for the printing simplifies the language, and allows the printing to be implemented in the language itself. In most newer languages of that era I/O is not part of the syntax. However the format was usually not checked to see if it matched the type (or even the number) of values being printed.<ref>{{cite web|url=https://owasp.org/www-community/attacks/Format_string_attack |title=Format String Attack}}</ref>

===1970s: C=== In 1973, {{code|printf}} was included as a C standard library routine as part of Version 4 Unix.<ref name="reader">{{cite tech report |first1=M. D. |last1=McIlroy |author-link1=Doug McIlroy |year=1987 |url=http://www.cs.dartmouth.edu/~doug/reader.pdf |title=A Research Unix reader: annotated excerpts from the Programmer's Manual, 1971–1986 |series=CSTR |number=139 |institution=Bell Labs}}</ref>

===1990s: Shell command=== In 1990, the <code>printf</code> shell command, modeled after the C standard library function, was included with 4.3BSD-Reno.<ref>{{cite web |title=printf (4.3+Reno BSD) |url=https://man.freebsd.org/cgi/man.cgi?query=printf&apropos=0&sektion=0&manpath=4.3BSD+Reno&arch=default&format=html |website=man.freebsd.org |access-date=2024-04-01}}</ref> In 1991, a {{code|printf}} command was included with GNU shellutils (now part of GNU Core Utilities) and the syntax (options, arguments, etc.) of this "''shell command''" are different from the ''C-Language function'' e.g.: the ''"format section"'' does not use the ''positional arguments''<ref>{{Cite web |title=Positional Parameters |url=https://tldp.org/LDP/abs/html/othertypesv.html#EX17 |access-date=2025-12-16 |website=tldp.org}}</ref> with a "$" symbol (n$) in the same way as <code>printf()</code> function:<syntaxhighlight lang="bash" line="1"> str="AA BB CC" # simple string with 3 fields set -- $str # convert fields to positional parameters printf "%s " $2 $3 $1; echo # in C printf() uses 2$ 3$.. # prints: BB CC AA </syntaxhighlight>

===2000s: Java=== In 2004, Java 5.0 (1.5) released, which extended the class <code>java.io.PrintStream</code>, adding a method named <code>printf()</code> which functions analogously to <code>printf()</code> in C. Thus to print a formatted string to the standard output stream, one uses <code>System.out.printf()</code>. Java further introduced the method <code>format</code> to its string class <code>java.lang.String</code>.<ref>{{Cite web|url=https://docs.oracle.com/en/java/javase/24/docs/api/java.base/java/io/PrintStream.html|title=Class PrintStream|publisher=docs.oracle.com|access-date=13 September 2025}}</ref>

===2000s: -Wformat safety=== The need to do something about the range of problems resulting from lack of type safety has prompted attempts to make compilers {{code|printf}}-aware.

The {{kbd|-Wformat}} option of GNU Compiler Collection (GCC) allows compile time checks to {{code|printf}} calls, enabling the compiler to detect a subset of invalid calls (and issue either a warning or an error, terminating compilation, as set by other flags).<ref>{{cite manual |section-url=https://gcc.gnu.org/onlinedocs/gcc-14.2.0/gcc/Warning-Options.html#index-Wformat |url=https://gcc.gnu.org/onlinedocs/gcc-14.2.0/gcc/ |section=3.8 Options to Request or Suppress Warnings |title=GCC 14.2 Manual |author=<!-- Name, Human --> |publisher=Free Software Foundation |year=2024 |access-date=2025-02-12}}</ref>

Because the compiler inspects {{code|printf}} format specifiers, this feature effectively extends static analysis in C to include formatting aspects.

===2020s: std::print ===

C++ added input/output support using the {{tt|<<}} operator to avoid safety issues of printf.<ref>{{cite journal|first=Bjarne|last=Stroustrup|authorlink=Bjarne Stroustrup|title=A history of C++: 1979–1991|date=March 1993|journal=ACM SIGPLAN Notices|volume=28|issue=3|pp=271–297|doi=10.1145/155360.155375|doi-access=free|publisher=Association for Computing Machinery|issn=0362-1340}}</ref> This used the type of the arguments to choose which code to execute to print them, avoiding the crashes that are possible with format strings. However, the syntax can be verbose (especially for setting options like precision), and {{tt|printf}} remains available in C++ and is often used instead.

C++20 added a new API which uses a string consisting of verbatim text and placeholders followed by the values to print.<ref name="collyer">{{cite journal|first=Spencer|last=Collyer|date=December 2021|title=C++20 Text Formatting: An Introduction|url=https://accu.org/journals/overload/29/166/collyer/|journal=Overload|volume=29|issue=166|pp=9–21|issn=1354-3172|publisher=ACCU|location=United Kingdom}}</ref> The format string uses curly braces instead of percent signs, based on the syntax used in the Python standard library:<ref name="collyer"/><ref>{{cite book|first=Marius|last=Bancila|year=2020|title=Modern C++ Programming Cookbook|publisher=Packt|edition=2nd|isbn=978-1-8002-0620-5|chapter=Working with Numbers and Strings|chapter-url=https://subscription.packtpub.com/book/programming/9781800208988/2}}</ref>

:{{code|lang=C++|std::format("The hex value of {} is {:x}.", name, value)}}

The recommended implementation is from Victor Zverovich's ''fmtlib''<ref name="collyer"/><ref>{{cite web|first=Victor|last=Zverovich|date=16 July 2019|url=https://www.open-std.org/jtc1/sc22/wg21/docs/papers/2019/p0645r10.html |title=Text Formatting|series=C++ Standards Committee Papers|publisher=Open Standards}}</ref> which at compile time converts the string and argument types into an optimized formatting object, this is type-safe and syntax errors are detected at compile time. C++23 introduced the functions {{code|std::print()|cpp}} and {{code|std::println()|cpp}} which combined formatting and outputting, and is therefore a functional replacement for {{code|printf()}}.<ref>{{cite book|first=Daniel|last=Kusswurm|date=November 2024|isbn=979-8-8688-0774-9|chapter=Formatted I/O|pp=63–103|title= Practical C++ STL Programming|publisher=Apress|location=Berkeley, California|chapter-url=https://link.springer.com/chapter/10.1007/979-8-8688-0774-9_2|chapter-url-access=subscription}}</ref> It is possible to make a translator from a printf %-string to the same formatting object<ref>{{Cite web|url=https://fmt.dev/12.0/api/#safe-printf|title=Safe printf}}</ref> and this could produce a type-safe {{tt|printf}}, but this was also not added to the spec. No analogous {{tt|scanf}} modernization has been introduced, though one has been proposed based on ''scnlib''.<ref>{{Cite web|first1=E.|last1=Kosunen|first2=V.|last2=Zverovich|url=https://www.open-std.org/jtc1/sc22/wg21/docs/papers/2024/p1729r5.html|title=P1729R5: Text Parsing|publisher=Open Standards|series=C++ Standards Committee Papers|date=15 October 2024}}</ref>

These functions (plus {{code|std::to_chars}}) can print floating point accurately using the least number of trailing digits possible, an ability long missing from {{tt|printf}}. Another useful feature is that they ignore the locale.

== Format specifier == Formatting of a value is specified as markup in the format string. For example, the following outputs <code>Your age is</code> and then the value of the variable {{var|age}} in decimal format.

<syntaxhighlight lang="c"> printf("Your age is %d", age); </syntaxhighlight>

===Syntax=== The syntax for a format specifier is: %[''parameter''][''flags''][''width''][.''precision''][''length'']''type''

===Parameter field=== The parameter field is optional. If included, then matching specifiers to values is {{em|not}} sequential. The numeric value {{samp|n}} selects the n-th value parameter. This is a POSIX extension, not C99.{{needs citation|date=April 2025}}

{{Table alignment}} {| class="wikitable col1center" |- ! Text ! Description |- | {{tt|''n''$}} | ''n'' is the index of the value parameter to serialize using this format specifier |}

This field allows for using the same value multiple times in a format string instead of having to pass the value multiple times. If a specifier includes this field, then subsequent specifiers must also.

For example, <syntaxhighlight lang="c"> printf("%2$d %2$#x; %1$d %1$#x",16,17); </syntaxhighlight> outputs: {{samp|17 0x11; 16 0x10}}

This field is very useful for localizing messages to different natural languages that use different word orders.

In the Windows API, support for this feature is via a different function, {{code|printf_p}}.

===Flags field=== The flags field can be zero or more of (in any order): {{Table alignment}} {| class="wikitable col1center" |- ! Text ! Description |- | {{tt|-}} |Left-align the output of this placeholder; default is to right-align the output |- | {{tt|+}} |Prepends a plus sign for a positive value; by default a positive value does not have a prefix |- | <code style="white-space:pre"> </code><br />(space) |Prepends a space character for a positive value; ignored if the {{tt|+}} flag exists; by default a positive value does not have a prefix |- | {{tt|0}} |When the 'width' option is specified, prepends zeros instead of spaces for numeric types; for example, {{code|printf("%4X",3)|c}} produces <samp style="white-space:pre">" 3"</samp>, while {{code|printf("%04X",3);|c}} produces {{samp|"0003"}} |- | {{tt|'}} | The integer or exponent of a decimal has the thousands grouping separator applied |- | {{tt|#}} | Alternate form:<br /> For {{tt|g}} and {{tt|G}} types, trailing zeros are not removed<br /> For {{tt|f}}, {{tt|F}}, {{tt|e}}, {{tt|E}}, {{tt|g}}, {{tt|G}} types, the output always contains a decimal point<br /> For {{tt|o}}, {{tt|x}}, {{tt|X}} types, the text {{tt|0}}, {{tt|0x}}, {{tt|0X}}, respectively, is prepended to non-zero numbers |}

===Width field=== The width field specifies the {{em|minimum}} number of characters to output. If the value can be represented in fewer characters, then the value is left-padded with spaces so that output is the number of characters specified. If the value requires more characters, then the output is longer than the specified width. A value is never truncated.

For example, {{code|printf("%3d", 12);|c}} specifies a width of 3 and outputs {{samp|12}} with a space on the left to output 3 characters. The call {{code|printf("%3d", 1234);|c}} outputs {{samp|1234}} which is 4 characters long since that is the minimum width for that value even though the width specified is 3.

If the width field is omitted, the output is the minimum number of characters for the value.

If the field is specified as {{code|*}}, then the width value is read from the list of values in the call.<ref>{{cite web |title=printf |url=http://www.cplusplus.com/reference/cstdio/printf/ |access-date=2020-06-10 |website=cplusplus.com}}</ref> For example, {{code|printf("%*d", 3, 10);|c}} outputs <samp style="white-space:pre"> 10</samp> (<space>10) where the second parameter, {{code|3|c}}, is the width (matches with {{code|*}}) and {{code|10|c}} is the value to serialize (matches with {{code|d}}).

Though not part of the width field, a leading zero is interpreted as the zero-padding flag mentioned above, and a negative value is treated as the positive value in conjunction with the left-alignment {{code|-}} flag also mentioned above.

The width field can be used to format values as a table (tabulated output). But, columns do not align if any value is larger than fits in the width specified. For example, notice that the last line value ({{samp|1234}}) does not fit in the first column of width 3 and therefore the column is not aligned.

<syntaxhighlight lang="output"> 1 1 12 12 123 123 1234 123 </syntaxhighlight>

===Precision field=== The precision field usually specifies a {{em|maximum}} limit of the output, as set by the formatting type. For floating-point numeric types, it specifies the number of digits to the right of the decimal point to which the output should be rounded; for {{code|%g}} and {{code|%G}} it specifies the total number of significant figures (before and after the decimal, not including leading or trailing zeroes) to round to. For the string type, it limits the number of characters that should be output, after which the string is truncated.

The precision field may be omitted, or a numeric integer value, or a dynamic value when passed as another argument when indicated by an asterisk ({{code|*}}). For example, {{code|printf("%.*s", 3, "abcdef");|c}} outputs {{samp|abc}}.

===Length field=== The length field can be omitted or be any of: {{Table alignment}} {| class="wikitable col1center" |- ! Text ! Description |- | {{tt|hh}} | For integer types, causes {{tt|printf}} to expect an {{tt|int}}-sized integer argument which was promoted from a {{tt|char}}. |- | {{tt|h}} | For integer types, causes {{tt|printf}} to expect an {{tt|int}}-sized integer argument which was promoted from a {{tt|short}}. |- | {{tt|l}} | For integer types, causes {{tt|printf}} to expect a {{tt|long}}-sized integer argument. For floating-point types, this is ignored. {{tt|float}} arguments are always promoted to {{tt|double}} when used in a varargs call.<ref name="c99io">{{cite tech report| publisher=ISO/IEC |year=1999 |title-link=C99 |title=ISO/IEC 9899:1999(E): Programming Languages – C |section=7.19.6.1 |at=para. 7}}</ref> |- | {{tt|ll}} | For integer types, causes {{tt|printf}} to expect a {{tt|long long}}-sized integer argument. |- | {{tt|L}} | For floating-point types, causes {{tt|printf}} to expect a {{tt|long double}} argument. |- | {{tt|z}} | For integer types, causes {{tt|printf}} to expect a {{tt|size_t}}-sized integer argument. |- | {{tt|j}} | For integer types, causes {{tt|printf}} to expect a {{tt|intmax_t}}-sized integer argument. |- | {{tt|t}} | For integer types, causes {{tt|printf}} to expect a {{tt|ptrdiff_t}}-sized integer argument. |}

Platform-specific length options came to exist prior to widespread use of the ISO C99 extensions, including: {{Table alignment}} {| class="wikitable col1center" |- ! Text ! Description ! ''Commonly found platforms'' |- | {{tt|I}} | For signed integer types, causes {{tt|printf}} to expect {{tt|ptrdiff_t}}-sized integer argument; for unsigned integer types, causes {{tt|printf}} to expect {{tt|size_t}}-sized integer argument || Win32/Win64 |- | {{tt|I32}} | For integer types, causes {{tt|printf}} to expect a 32-bit (double word) integer argument || Win32/Win64 |- | {{tt|I64}} | For integer types, causes {{tt|printf}} to expect a 64-bit (quad word) integer argument || Win32/Win64 |- | {{tt|q}} | For integer types, causes {{tt|printf}} to expect a 64-bit (quad word) integer argument || BSD |}

ISO C99 includes the <code>inttypes.h</code> header file that includes a number of macros for cross-platform {{code|printf}} coding. For example: {{code|printf("%" PRId64, t);|c}} specifies decimal format for a 64-bit signed integer. Since the macros evaluate to a string literal, and the compiler concatenates adjacent string literals, the expression {{code|"%" PRId64|c}} compiles to a single string.

Macros include: {| class="wikitable" |- ! Macro ! Description |- | {{tt|PRId32}} | Typically equivalent to {{tt|I32d}} (''Win32/Win64'') or {{tt|d}} |- | {{tt|PRId64}} | Typically equivalent to {{tt|I64d}} (''Win32/Win64''), {{tt|lld}} (''32-bit platforms'') or {{tt|ld}} (''64-bit platforms'') |- | {{tt|PRIi32}} | Typically equivalent to {{tt|I32i}} (''Win32/Win64'') or {{tt|i}} |- | {{tt|PRIi64}} | Typically equivalent to {{tt|I64i}} (''Win32/Win64''), {{tt|lli}} (''32-bit platforms'') or {{tt|li}} (''64-bit platforms'') |- | {{tt|PRIu32}} | Typically equivalent to {{tt|I32u}} (''Win32/Win64'') or {{tt|u}} |- | {{tt|PRIu64}} | Typically equivalent to {{tt|I64u}} (''Win32/Win64''), {{tt|llu}} (''32-bit platforms'') or {{tt|lu}} (''64-bit platforms'') |- | {{tt|PRIx32}} | Typically equivalent to {{tt|I32x}} (''Win32/Win64'') or {{tt|x}} |- | {{tt|PRIx64}} | Typically equivalent to {{tt|I64x}} (''Win32/Win64''), {{tt|llx}} (''32-bit platforms'') or {{tt|lx}} (''64-bit platforms'') |}

===Type field=== The type field can be any of: {{Table alignment}} {| class="wikitable col1center" |- ! Text ! Description |- | {{tt|%}} |Output a literal {{tt|%}} character; does not accept flags, width, precision or length fields |- | {{tt|d}}, {{tt|i}} |(signed) {{tt|int}} formatted as decimal; {{tt|%d}} and {{tt|%i}} are synonymous except when used with <code>scanf</code> |- | {{tt|u}} | {{tt|unsigned int}} formatted as decimal. |- | {{tt|f}}, {{tt|F}} |{{tt|double}} formatted as fixed-point; {{tt|f}} and {{tt|F}} only differs in how the strings for an infinite number or NaN are printed ({{tt|inf}}, {{tt|infinity}} and {{tt|nan}} for {{tt|f}}; {{tt|INF}}, {{tt|INFINITY}} and {{tt|NAN}} for {{tt|F}}) |- | {{tt|e}}, {{tt|E}} |{{tt|double}} formatted as in exponential notation {{tt|''d''.''ddd''e±''dd''}}; {{tt|E}} results in {{tt|E}} rather than {{tt|e}} to introduce the exponent; the exponent always contains at least two digits; if the value is zero, the exponent is {{tt|00}}; in Windows, the exponent contains three digits by default, e.g. {{tt|1.5e002}}, but this can be altered by Microsoft-specific {{code|_set_output_format}} function |- | {{tt|g}}, {{tt|G}} |{{tt|double}} formatted as either fixed-point or exponential notation, whichever is more appropriate for its magnitude; {{tt|g}} uses lower-case letters, {{tt|G}} uses upper-case letters; this type differs slightly from fixed-point notation in that insignificant zeroes to the right of the decimal point are not included, and that the precision field specifies the total number of significant digits rather than the digits after the decimal; the decimal point is not included on whole numbers |- | {{tt|x}}, {{tt|X}} |{{tt|unsigned int}} formatted as hexadecimal; {{tt|x}} uses lower-case letters and {{tt|X}} uses upper-case |- | {{tt|o}} |{{tt|unsigned int}} formatted as octal |- | {{tt|s}} |null-terminated string |- | {{tt|c}} |{{tt|char}} |- | {{tt|p}} |Pointer formatted in an implementation-defined way |- | {{tt|a}}, {{tt|A}} |{{tt|double}} in hexadecimal notation, starting with {{tt|0x}} or {{tt|0X}}. {{tt|a}} uses lower-case letters, {{tt|A}} uses upper-case letters<ref>{{cite book|title=Modern C|first=Jens|last=Gustedt|date=15 October 2024|chapter=C library functions|url=https://inria.hal.science/hal-02383654|isbn=9781617295812|publisher=Inria|p=120}}</ref> |- | {{tt|n}} | Outputs nothing but writes the number of characters written so far into an integer pointer parameter; in Java this prints a newline<ref>{{cite book|first1=H.|last1=Schildt|first2=D.|last2=Coward|year=2024|title=Java: The Complete Reference|edition=13th|editor-first=S.|editor-last=Ritter|publisher=McGraw Hill|isbn=978-1-265-05843-2|url=https://www.mheducation.com/highered/mhp/product/java-complete-reference-thirteenth-edition.html|url-access=subscription|chapter=java.util Part 2: More Utility Classes|pp=667–726}}</ref> |}

=== Custom data type formatting === A common way to handle formatting with a custom data type is to format the custom data type value into a string, then use the {{code|%s|c}} specifier to include the serialized value in a larger message.

Some printf-like functions allow extensions to the escape-character-based mini-language, thus allowing the programmer to use a specific formatting function for non-builtin types. One is the (now deprecated) glibc's [https://www.gnu.org/software/libc/manual/html_node/Customizing-Printf.html {{code|register_printf_function()}}]. However, it is rarely used due to the fact that it conflicts with static format string checking. Another is [http://www.and.org/vstr/#cust-fmt Vstr custom formatters], which allows adding multi-character format names.

Some applications (like the Apache HTTP Server) include their own printf-like function, and embed extensions into it. However these all tend to have the same problems that {{code|register_printf_function()}} has.

The Linux kernel <code>printk</code> function supports a number of ways to display kernel structures using the generic {{code|%p|c}} specification, by {{em|appending}} additional format characters.<ref>{{cite report |last1=Dunlap |first1=Randy |last2=Murray |first2=Andrew |date=n.d. |url=https://docs.kernel.org/core-api/printk-formats.html |chapter=How to get printk format specifiers right |title=The Linux Kernel documentation |publisher=Linux Foundation |access-date=2025-02-12 |archive-date=2025-02-06 |archive-url=https://web.archive.org/web/20250206200419/https://docs.kernel.org/core-api/printk-formats.html |url-status=live}}</ref> For example, {{code|%pI4|c}} prints an IPv4 address in dotted-decimal form. This allows static format string checking (of the {{code|%p|c}} portion) at the expense of full compatibility with normal printf.

==Vulnerabilities== === Format string attack === Extra value arguments are ignored, but if the format string has more format specifiers than value arguments passed, the behavior is undefined. For some C compilers, an extra format specifier results in consuming a value even though there isn't one which allows the format string attack. Generally, for C, arguments are passed on the stack. If too few arguments are passed, then printf can read past the end of the stack frame, thus allowing an attacker to read the stack.

Some compilers, like the GNU Compiler Collection, will statically check the format strings of printf-like functions and warn about problems (when using the flags {{kbd|-Wall}} or {{kbd|-Wformat}}). GCC will also warn about user-defined printf-style functions if the non-standard "format" {{code|__attribute__}} is applied to the function.

===Uncontrolled format string exploit=== The format string is often a string literal, which allows static analysis of the function call. However, the format string can be the value of a variable, which allows for dynamic formatting but also a security vulnerability known as an uncontrolled format string exploit.

===Memory write=== Although an output function on the surface, {{code|printf}} allows writing to a memory location specified by an argument via {{code|%n|c}}. This functionality can be used for code injection attacks without violating control-flow integrity.<ref name="usenix">{{cite conference|last1=Carlini|first1=N.|last2=Barresi|first2=A.|last3=Payer|first3=M.|last4=Wagner|first4=D.|last5=Gross|first5=T. R.|title=Control-flow bending: on the effectiveness of control-flow integrity|conference=SEC'15|book-title=Proceedings of the 24th USENIX Conference on Security Symposium|pp=161–176|date=12 August 2015|publisher=USENIX|location=Washington, D.C.|isbn=978-1-931971-23-2|s2cid=2165728|url=https://www.usenix.org/system/files/conference/usenixsecurity15/sec15-paper-carlini.pdf}}</ref>

The {{code|%n|c}} format specifier also makes {{code|printf}} accidentally Turing-complete even with a well-formed set of arguments.<ref name="usenix"/> A game of tic-tac-toe written in the format string is a winner of the 27th IOCCC.<ref>{{cite news |last1=Carlini |first1=Nicholas |author1-link=Nicholas Carlini |others=Judges: Leonid A. Broukhis, Landon Curt Noll |year=2020 |url=https://www.ioccc.org/2020/carlini/ |title=printf machine |work=International Obfuscated C Code Contest |publisher=Landon Curt Noll |access-date=2025-02-12}}</ref>

==Related functions== ===Family=== Variants of {{code|printf}} in the C standard library include: {{code|fprintf}} outputs to a file instead of standard output.

{{code|sprintf}} writes to a string buffer instead of standard output.

{{code|snprintf}} provides a level of safety over {{code|sprintf}} since the caller provides a length ''n'' that is the length of the output buffer in bytes (including space for the trailing null character).

{{code|asprintf}} provides for safety by accepting a string handle (<code>char**</code>) argument. The function allocates a buffer of sufficient size to contain the formatted text and outputs the buffer via the handle.

For each function of the family, including printf, there is also a variant that accepts a single {{code|va_list}} argument rather than a variable list of arguments. Typically, these variants start with "v". For example: {{code|vprintf}}, {{code|vfprintf}}, {{code|vsprintf}}.

Generally, printf-like functions return the number of bytes output or -1 to indicate failure.<ref>{{cite web |last=Kerrisk |first=Michael |date=Feb 2, 2025 |title=sprintf(3) — Linux manual page |website=man7.org |url=https://man7.org/linux/man-pages/man3/sprintf.3.html |access-date=March 19, 2025}}</ref>

===Other contexts=== The following list includes notable programming languages that provide (directly or via a standard library) functioning that is the same or similar to the C printf-like functions. Excluded are languages that use format strings that deviate from the style in this article (such as AMPL and Elixir), languages that inherit their implementation from the Java virtual machine (JVM) or other environment (such as Clojure and Scala), and languages that do not have a standard native printf implementation but have external libraries which emulate printf behavior (such as JavaScript).

{{div col}} *awk<ref>{{cite tech report |url=https://pubs.opengroup.org/onlinepubs/9699919799/utilities/awk.html#tag_20_06_13_10 |chapter=POSIX awk, Output Statements |title=The Open Group Base Specifications, Issue 7 |edition=2018 |website=pubs.opengroup.org |publisher=The Open Group |access-date=2022-05-29}}</ref> *C *C++ *D *F# *G *GNU MathProg *GNU Octave *Go *Haskell *J *Java (since version 1.5) and JVM languages *Julia (via Printf standard library<ref>{{cite web |title=Printf Standard Library |url=https://docs.julialang.org/en/v1/stdlib/Printf/ |website=The Julia Language Manual |access-date=22 February 2021}}</ref>) *Lua ({{code|string.format|lua}}) *Maple *MATLAB *Max (via the {{code|sprintf}} object) *Objective-C *OCaml (via Printf module) *PARI/GP *Perl **Raku (via {{code|printf|raku}}, {{code|sprintf|raku}}, and {{code|fmt|raku}}) *PHP *Python (via {{code|%|python}} operator)<ref>{{citation |title=The Python Standard Library |section=Built-in Types: <code>printf</code>-style String Formatting |publisher=Python Software Foundation |section-url=https://docs.python.org/library/stdtypes.html#old-string-formatting |access-date=2021-02-24}}</ref> *R *Red/System *Ruby *SQLite<ref>{{cite web |title=SQLite's Built-in printf() |url=https://sqlite.org/printf.html |website=sqlite.org |access-date=24 November 2025}}</ref> *Tcl (via {{code|format}} command) *Transact-SQL (via [https://technet.microsoft.com/en-us/library/ms175014.aspx {{code|xp_sprintf}}]) *Vala (via {{code|print()}} and {{code|FileStream.printf()}}) {{div col end}}

==See also== * "Hello, World!" program{{snd}} A basic example program first featured in ''The C Programming Language'' (the "K&R Book"), which in the C example uses printf to output the message "Hello, World!" * {{Annotated link |Format (Common Lisp)}} * {{Annotated link |C standard library}} * {{Annotated link |Format string attack}} * {{Annotated link |Input/output (C++)}} * {{Annotated link |printf debugging}} * {{Annotated link |printf (Unix)|{{mono|printf}} (Unix)}} * {{Annotated link |printk|{{mono|printk}}}} * {{Annotated link |scanf|{{mono|scanf}}}} * {{Annotated link |string interpolation}}

==Notes== {{Notelist}}

==References== {{Reflist}}

==External links== *[http://en.cppreference.com/w/cpp/io/c/fprintf C++ reference for {{code|std::fprintf|cpp}}] *[http://www.pixelbeat.org/programming/gcc/format_specs.html gcc printf format specifications quick reference] *{{man|sh|printf|SUS|print formatted output}} *The [http://java.sun.com/j2se/1.5.0/docs/api/java/util/Formatter.html {{code|Formatter|java}} specification] in Java 1.5 *GNU Bash [http://wiki.bash-hackers.org/commands/builtin/printf {{code|printf(1)}} builtin]

{{CProLang}} {{Unix commands}}

Category:C standard library Category:Unix software <!-- Hidden categories below --> Category:Articles with example ALGOL 68 code Category:Articles with example C code Category:Articles with example Fortran code