Share
VIDEOS 1 TO 50
Print Formatting Part 1: printf() Conversion Type Characters (Java)
Print Formatting Part 1: printf() Conversion Type Characters (Java)
Published: 2013/10/29
Channel: Nathan Schutz
Input and Output:  Printf and Scanf - C Programming Tutorial 06
Input and Output: Printf and Scanf - C Programming Tutorial 06
Published: 2014/05/28
Channel: mycodeschool
14 - Formatted Strings ( printf; format ) | Java Tutorials
14 - Formatted Strings ( printf; format ) | Java Tutorials
Published: 2016/07/21
Channel: SimplyCoded
Java Tutorial 8 - Formatting Output with printf
Java Tutorial 8 - Formatting Output with printf
Published: 2013/12/10
Channel: Sam
A simple Format String exploit example - bin 0x11
A simple Format String exploit example - bin 0x11
Published: 2016/04/09
Channel: LiveOverflow
4.2 How to use Printf method in Java
4.2 How to use Printf method in Java
Published: 2015/03/16
Channel: Telusko Learnings
C++ Part 19 - Output With printf
C++ Part 19 - Output With printf
Published: 2012/06/17
Channel: ICT Tutorial Channel
RUBY Formatting strings with SPRINTF and PRINTF
RUBY Formatting strings with SPRINTF and PRINTF
Published: 2013/10/13
Channel: theurbanpenguin
Handmade Hero Day 327 - Parsing Printf Format Strings
Handmade Hero Day 327 - Parsing Printf Format Strings
Published: 2016/08/16
Channel: Handmade Hero
06 Using The printf Command To Format A String
06 Using The printf Command To Format A String
Published: 2014/05/28
Channel: Beche Melisa
Print Formatting Part 3: printf() Precision (Java)
Print Formatting Part 3: printf() Precision (Java)
Published: 2013/10/30
Channel: Nathan Schutz
Print Formatting Part 4: printf() Width (Java)
Print Formatting Part 4: printf() Width (Java)
Published: 2013/10/30
Channel: Nathan Schutz
Printf format string
Printf format string
Published: 2014/08/18
Channel: Audiopedia
06 | Printf Function in C Programming Language Video Tutorials
06 | Printf Function in C Programming Language Video Tutorials
Published: 2013/04/23
Channel: LearningLad
Introduction to format string vulnerabilities
Introduction to format string vulnerabilities
Published: 2013/04/30
Channel: Pico Cetef
String Formatting - Python: Tutorial 24
String Formatting - Python: Tutorial 24
Published: 2014/08/12
Channel: Coding Basics
46. Printf integer right and left justified in C Programming (Hindi)
46. Printf integer right and left justified in C Programming (Hindi)
Published: 2015/09/13
Channel: Geeky Shows
Print Formatting Part 2: printf() Multiple Statements (Java)
Print Formatting Part 2: printf() Multiple Statements (Java)
Published: 2013/10/29
Channel: Nathan Schutz
Printf and Scanf in C Language HIndi tutorial-5
Printf and Scanf in C Language HIndi tutorial-5
Published: 2015/02/09
Channel: computer programming trends
Print Formatting Part 12: printf() argument index (Java)
Print Formatting Part 12: printf() argument index (Java)
Published: 2013/11/01
Channel: Nathan Schutz
15JAVA FORMATTING PRINTF FUNCTION (IN HINDI)
15JAVA FORMATTING PRINTF FUNCTION (IN HINDI)
Published: 2015/04/14
Channel: LearnEveryone
Python 3 Tutorial: 18 - Formatting
Python 3 Tutorial: 18 - Formatting
Published: 2010/12/23
Channel: TheMonkeyLords
C++/Game Tutorial 20: printf, C-Strings, and Documentation!
C++/Game Tutorial 20: printf, C-Strings, and Documentation!
Published: 2014/06/13
Channel: MakingGamesWithBen
Intro to Java Programming 18 - printf
Intro to Java Programming 18 - printf
Published: 2012/01/11
Channel: FakeNoobTutorials
Java Programming Tutorial 2; Formatted Output with Printf
Java Programming Tutorial 2; Formatted Output with Printf
Published: 2016/01/03
Channel: Flamur B.
Print Formatting Part 8: printf() Flag 0 (Java)
Print Formatting Part 8: printf() Flag 0 (Java)
Published: 2013/10/31
Channel: Nathan Schutz
78 Formatted Output Printf PT1
78 Formatted Output Printf PT1
Published: 2014/12/28
Channel: c language.chanal
Java - Formatting Strings
Java - Formatting Strings
Published: 2014/09/10
Channel: Cov Cath Computer Programming
[FuzzySecurity] Format String Exploitation - Part1
[FuzzySecurity] Format String Exploitation - Part1
Published: 2013/04/07
Channel: skorpioPZ
Notation, Precision and Formatting with printf() in Java - Part 1
Notation, Precision and Formatting with printf() in Java - Part 1
Published: 2010/07/18
Channel: Carly Salali
Visual C# 2010 Lesson 8 - Converting Numbers to Formatted Strings
Visual C# 2010 Lesson 8 - Converting Numbers to Formatted Strings
Published: 2011/04/14
Channel: Lecture Snippets
Software security - Format String Vulnerabilities
Software security - Format String Vulnerabilities
Published: 2016/08/30
Channel: intrigano
Java Basics - printf
Java Basics - printf
Published: 2013/01/04
Channel: MargretPosch
Formatted Output with printf and format
Formatted Output with printf and format
Published: 2014/11/07
Channel: Samir Paul
Formatting Output with printf in Java
Formatting Output with printf in Java
Published: 2014/08/19
Channel: Tom Wulf
Handmade Hero Day 328 - Integer and String Support in Printf
Handmade Hero Day 328 - Integer and String Support in Printf
Published: 2016/08/17
Channel: Handmade Hero
3. Printf Scanf and Format Specifier in C
3. Printf Scanf and Format Specifier in C
Published: 2017/07/17
Channel: Weekend Class
Lecture-12 format specifiers in C and printf
Lecture-12 format specifiers in C and printf
Published: 2017/02/06
Channel: MyTechValley
C Programming Tutorial: Input Output (printf, scanf, format specifiers) Lesson 1
C Programming Tutorial: Input Output (printf, scanf, format specifiers) Lesson 1
Published: 2012/04/23
Channel: saurabhschool
Lesson 6a Formatting output with printf
Lesson 6a Formatting output with printf
Published: 2017/10/15
Channel: SIM Java Tutor
C - stdout printf formatting
C - stdout printf formatting
Published: 2016/12/24
Channel: Nowhere Fast
Strings and printf - Python: Tutorial 4
Strings and printf - Python: Tutorial 4
Published: 2014/06/08
Channel: Coding Basics
Print Formatting Part 10: printf() Flag ( (Java)
Print Formatting Part 10: printf() Flag ( (Java)
Published: 2013/10/31
Channel: Nathan Schutz
Java printf method introduction
Java printf method introduction
Published: 2016/11/07
Channel: Brian Fleischman
C Programming Tutorial 10 - C Basics Part 2 - Print Variables Using Printf
C Programming Tutorial 10 - C Basics Part 2 - Print Variables Using Printf
Published: 2017/03/29
Channel: CalebTheVideoMaker2
Print Formatting Part 5: printf() Flag - (JAVA)
Print Formatting Part 5: printf() Flag - (JAVA)
Published: 2013/10/31
Channel: Nathan Schutz
C Programming Language Tutorial in Hindi 40 Formatted Printf
C Programming Language Tutorial in Hindi 40 Formatted Printf
Published: 2015/02/08
Channel: Champion Mahipal
Replacing printf
Replacing printf
Published: 2015/05/06
Channel: Jonathan Blow
C Programming Tutorial - 11 - Getting Input with scanf
C Programming Tutorial - 11 - Getting Input with scanf
Published: 2014/08/04
Channel: thenewboston
printf & format
printf & format
Published: 2016/03/19
Channel: PurdueX CS180.1x
NEXT
GO TO RESULTS [51 .. 100]

WIKIPEDIA ARTICLE

From Wikipedia, the free encyclopedia
  (Redirected from Printf)
Jump to: navigation, search
An example of the printf function.

Printf format string (of which "printf" stands for "print formatted") refers to a control parameter used by a class of functions in the string-processing libraries of various programming languages. The format string is written in a simple template language, and specifies a method for rendering an arbitrary number of varied data type parameters into a string. This string is then by default printed on the standard output stream, but variants exist that perform other tasks with the result, such as returning it as the value of the function. Characters in the format string are usually copied literally into the function's output, as is usual for templates, with the other parameters being rendered into the resulting text in place of certain placeholders – points marked by format specifiers, which are typically introduced by a % character, though syntax varies. The format string itself is very often a string literal, which allows static analysis of the function call. However, it can also be the value of a variable, which allows for dynamic formatting but also a security vulnerability known as an uncontrolled format string exploit.

The term "printf" is due to the C language, which popularized this type of function, but these functions predate C, and other names are used, notably "format". Printf format strings, which provide formatted output (templating), are complementary to scanf format strings, which provide formatted input (parsing). In both cases these provide simple functionality and fixed format compared to more sophisticated and flexible template engines or parsers, but are sufficient for many purposes.

Overview and history[edit]

Many programming languages implement a printf function to output a formatted string. It originated from the C programming language, where it has a prototype similar to the following:

int printf(const char *format, ...);

The string constant format provides a description of the output, with placeholders marked by % escape characters, to specify both the relative location and the type of output that the function should produce. The return value yields the number of printed characters.

printf("Color %s, number1 %d, number2 %05d, hex %#x, float %5.2f, unsigned value %u.\n",
       "red", 123456, 89, 255, 3.14159, 250);

will print the following line (including new-line character, \n):

Color red, number1 123456, number2 00089, hex 0xff, float  3.14, unsigned value 250.

The printf function returns the number of characters printed, or a negative value if an output error occurs.

History[edit]

C's variadic printf has its origins in BCPL's writef function (1966). For example, a statement to write the factorial equation 5! = 120 (assuming I is 5 and FACT computes the factorial) could be:[1]

WRITEF("%N! = %I4*N", I, FACT(I))

ALGOL 68 Draft and Final report had the functions inf and outf, subsequently these were revised out of the original language and replaced with the now more familiar readf/getf and printf/putf.

printf(($"Color "g", number1 "6d,", number2 "4zd,", hex "16r2d,", float "-d.2d,", unsigned value"-3d"."l$,
            "red", 123456, 89, BIN 255, 3.14, 250));

Unix printf first appeared in Version 4, as part of the porting to C.[2]

Format placeholder specification[edit]

Formatting takes place via placeholders within the format string. For example, if a program wanted to print out a person's age, it could present the output by prefixing it with "Your age is ". To denote that we want the integer for the age to be shown immediately after that message, we may use the format string:

"Your age is %d."

Syntax[edit]

The syntax for a format placeholder is

%[parameter][flags][width][.precision][length]type

Parameter field[edit]

This is a POSIX extension and not in C99. The Parameter field can be omitted or can be:

Character Description
n$ n is the number of the parameter to display using this format specifier, allowing the parameters provided to be output multiple times, using varying format specifiers or in different orders. If any single placeholder specifies a parameter, all the rest of the placeholders MUST also specify a parameter.
For example, printf("%2$d %2$#x; %1$d %1$#x",16,17) produces 17 0x11; 16 0x10.

Flags field[edit]

The Flags field can be zero or more (in any order) of:

Character Description
-
(minus)
Left-align the output of this placeholder. (The default is to right-align the output.)
+
(plus)
Prepends a plus for positive signed-numeric types. positive = +, negative = -.
(The default doesn't prepend anything in front of positive numbers.)
 
(space)
Prepends a space for positive signed-numeric types. positive =  , negative = -. This flag is ignored if the + flag exists.
(The default doesn't prepend anything in front of positive numbers.)
0
(zero)
When the 'width' option is specified, prepends zeros for numeric types. (The default prepends spaces.)
For example, printf("%2X",3) produces  3, while printf("%02X",3) produces in 03.
#
(hash)
Alternate form:
For g and G types, trailing zeros are not removed.
For f, F, e, E, g, G types, the output always contains a decimal point.
For o, x, X types, the text 0, 0x, 0X, respectively, is prepended to non-zero numbers.

Width field[edit]

The Width field specifies a minimum number of characters to output, and is typically used to pad fixed-width fields in tabulated output, where the fields would otherwise be smaller, although it does not cause truncation of oversized fields.

The width field may be omitted, or a numeric integer value, or a dynamic value when passed as another argument when indicated by an asterisk *. For example, printf("%*d", 5, 10) will result in    10 being printed, with a total width of 5 characters.

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 - flag also mentioned above.

Precision field[edit]

The Precision field usually specifies a maximum limit on the output, depending on the particular formatting type. For floating point numeric types, it specifies the number of digits to the right of the decimal point that the output should be rounded. 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 *. For example, printf("%.*s", 3, "abcdef") will result in abc being printed.

Length field[edit]

The Length field can be omitted or be any of:

Character Description
hh For integer types, causes printf to expect an int-sized integer argument which was promoted from a char.
h For integer types, causes printf to expect an int-sized integer argument which was promoted from a short.
l For integer types, causes printf to expect a long-sized integer argument.

For floating point types, causes printf to expect a double argument.

ll For integer types, causes printf to expect a long long-sized integer argument.
L For floating point types, causes printf to expect a long double argument.
z For integer types, causes printf to expect a size_t-sized integer argument.
j For integer types, causes printf to expect a intmax_t-sized integer argument.
t For integer types, causes printf to expect a ptrdiff_t-sized integer argument.

Additionally, several platform-specific length options came to exist prior to widespread use of the ISO C99 extensions:

Characters Description
I For signed integer types, causes printf to expect ptrdiff_t-sized integer argument; for unsigned integer types, causes printf to expect size_t-sized integer argument. Commonly found in Win32/Win64 platforms.
I32 For integer types, causes printf to expect a 32-bit (double word) integer argument. Commonly found in Win32/Win64 platforms.
I64 For integer types, causes printf to expect a 64-bit (quad word) integer argument. Commonly found in Win32/Win64 platforms.
q For integer types, causes printf to expect a 64-bit (quad word) integer argument. Commonly found in BSD platforms.

ISO C99 includes the inttypes.h header file that includes a number of macros for use in platform-independent printf coding. These need to not be inside double-quotes, e.g. printf("%" PRId64 "\n", t);

Example macros include:

Macro Description
PRId32 Typically equivalent to I32d (Win32/Win64) or d
PRId64 Typically equivalent to I64d (Win32/Win64), lld (32-bit platforms) or ld (64-bit platforms)
PRIi32 Typically equivalent to I32i (Win32/Win64) or i
PRIi64 Typically equivalent to I64i (Win32/Win64), lli (32-bit platforms) or li (64-bit platforms)
PRIu32 Typically equivalent to I32u (Win32/Win64) or u
PRIu64 Typically equivalent to I64u (Win32/Win64), llu (32-bit platforms) or lu (64-bit platforms)
PRIx32 Typically equivalent to I32x (Win32/Win64) or x
PRIx64 Typically equivalent to I64x (Win32/Win64), llx (32-bit platforms) or lx (64-bit platforms)

Type field[edit]

The Type field can be any of:

Character Description
% Prints a literal % character (this type doesn't accept any flags, width, precision, length fields).
d, i int as a signed decimal number. %d and %i are synonymous for output, but are different when used with scanf() for input (where using %i will interpret a number as hexadecimal if it's preceded by 0x, and octal if it's preceded by 0.)
u Print decimal unsigned int.
f, F double in normal (fixed-point) notation. f and F only differs in how the strings for an infinite number or NaN are printed (inf, infinity and nan for f, INF, INFINITY and NAN for F).
e, E double value in standard form ([-]d.ddd e[+/-]ddd). An E conversion uses the letter E (rather than e) to introduce the exponent. The exponent always contains at least two digits; if the value is zero, the exponent is 00. In Windows, the exponent contains three digits by default, e.g. 1.5e002, but this can be altered by Microsoft-specific _set_output_format function.
g, G double in either normal or exponential notation, whichever is more appropriate for its magnitude. g uses lower-case letters, 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. Also, the decimal point is not included on whole numbers.
x, X unsigned int as a hexadecimal number. x uses lower-case letters and X uses upper-case.
o unsigned int in octal.
s null-terminated string.
c char (character).
p void * (pointer to void) in an implementation-defined format.
a, A double in hexadecimal notation, starting with 0x or 0X. a uses lower-case letters, A uses upper-case letters.[3][4] (C++11 iostreams have a hexfloat that works the same).
n Print nothing, but writes the number of characters successfully written so far into an integer pointer parameter.
Note: This can be utilized in Uncontrolled format string exploits.

Custom format placeholders[edit]

There are a few implementations of printf-like functions that allow extensions to the escape-character-based mini-language, thus allowing the programmer to have a specific formatting function for non-builtin types. One of the most well-known is the (now deprecated) glibc's register_printf_function(). However, it is rarely used due to the fact that it conflicts with static format string checking. Another is Vstr custom formatters, which allows adding multi-character format names, and can work with static format checkers.

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 register_printf_function() has.

The Linux kernel printk function supports a number of ways to display kernel structures using the generic %p specification, by appending additional format characters.[5] For example, %pI4 prints an IPV4 address in dotted-decimal form. This allows static format string checking (of the %p portion) at the expense of full compatibility with normal printf.

Most non-C languages that have a printf-like function work around the lack of this feature by just using the %s format and converting the object to a string representation. C++ offers a notable exception, in that it has a printf function inherited from its C history, but also has a completely different mechanism that is preferred.

Vulnerabilities[edit]

Invalid conversion specifications[edit]

If the syntax of a conversion specification is invalid, behavior is undefined, and can cause program termination. If there are too few function arguments provided to supply values for all the conversion specifications in the template string, or if the arguments are not of the correct types, the results are also undefined. Excess arguments are ignored. In a number of cases, the undefined behavior has led to "Format string attack" security vulnerabilities.

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 -Wall or -Wformat). GCC will also warn about user-defined printf-style functions if the non-standard "format" __attribute__ is applied to the function.

Field width versus explicit delimiters in tabular output[edit]

Using only field widths to provide for tabulation, as with a format like %8d%8d%8d for three integers in three 8-character columns, will not guarantee that field separation will be retained if large numbers occur in the data. Loss of field separation can easily lead to corrupt output. In systems which encourage the use of programs as building blocks in scripts, such corrupt data can often be forwarded into and corrupt further processing, regardless of whether the original programmer expected the output would only be read by human eyes. Such problems can be eliminated by including explicit delimiters, even spaces, in all tabular output formats. Simply changing the dangerous example from before to  %7d %7d %7d addresses this, formatting identically until numbers become larger, but then explicitly preventing them from becoming merged on output due to the explicitly included spaces. Similar strategies apply to string data.

Programming languages with printf[edit]

Some languages, like AMPL and Elixir, use format strings that deviate from the style in this article. They are not included.

Other languages, like Clojure and Scala, inherit their implementation from JVM or other environment. They are not included.

Some languages, like JavaScript, do not have a standard native printf implementation but external libraries, like printj, emulate printf behavior. They are not included.

The printf utility command, sometimes built in the shell like some implementations of the Korn shell (ksh), Bourne again shell (bash), or Z shell (zsh).

See also[edit]

References[edit]

External links[edit]

Disclaimer

None of the audio/visual content is hosted on this site. All media is embedded from other sites such as GoogleVideo, Wikipedia, YouTube etc. Therefore, this site has no control over the copyright issues of the streaming media.

All issues concerning copyright violations should be aimed at the sites hosting the material. This site does not host any of the streaming media and the owner has not uploaded any of the material to the video hosting servers. Anyone can find the same content on Google Video or YouTube by themselves.

The owner of this site cannot know which documentaries are in public domain, which has been uploaded to e.g. YouTube by the owner and which has been uploaded without permission. The copyright owner must contact the source if he wants his material off the Internet completely.

Powered by YouTube
Wikipedia content is licensed under the GFDL and (CC) license