1 .\" Copyright (c) 1990, 1991, 1993
2 .\" The Regents of the University of California. All rights reserved.
4 .\" This code is derived from software contributed to Berkeley by
5 .\" Chris Torek and the American National Standards Committee X3,
6 .\" on Information Processing Systems.
8 .\" Redistribution and use in source and binary forms, with or without
9 .\" modification, are permitted provided that the following conditions
11 .\" 1. Redistributions of source code must retain the above copyright
12 .\" notice, this list of conditions and the following disclaimer.
13 .\" 2. Redistributions in binary form must reproduce the above copyright
14 .\" notice, this list of conditions and the following disclaimer in the
15 .\" documentation and/or other materials provided with the distribution.
16 .\" 4. Neither the name of the University nor the names of its contributors
17 .\" may be used to endorse or promote products derived from this software
18 .\" without specific prior written permission.
20 .\" THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
21 .\" ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
22 .\" IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
23 .\" ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
24 .\" FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
25 .\" DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
26 .\" OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
27 .\" HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
28 .\" LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
29 .\" OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
32 .\" @(#)printf.3 8.1 (Berkeley) 6/4/93
33 .\" $FreeBSD: src/lib/libc/stdio/printf.3,v 1.63 2009/03/04 03:38:51 das Exp $
34 .\" $DragonFly: src/lib/libc/stdio/printf.3,v 1.6 2006/08/26 10:27:55 swildner Exp $
52 .Nd formatted output conversion
56 .Fd "#define _WITH_DPRINTF"
59 .Fn printf "const char * restrict format" ...
61 .Fn fprintf "FILE * restrict stream" "const char * restrict format" ...
63 .Fn sprintf "char * restrict str" "const char * restrict format" ...
65 .Fn snprintf "char * restrict str" "size_t size" "const char * restrict format" ...
67 .Fn asprintf "char **ret" "const char *format" ...
69 .Fn dprintf "int" "const char * restrict format" ...
72 .Fn vprintf "const char * restrict format" "va_list ap"
74 .Fn vfprintf "FILE * restrict stream" "const char * restrict format" "va_list ap"
76 .Fn vsprintf "char * restrict str" "const char * restrict format" "va_list ap"
78 .Fn vsnprintf "char * restrict str" "size_t size" "const char * restrict format" "va_list ap"
80 .Fn vasprintf "char **ret" "const char *format" "va_list ap"
82 .Fn vdprintf "int fd" "const char * restrict format" "va_list ap"
86 family of functions produces output according to a
96 the standard output stream;
100 write output to the given output
105 write output to the given file descriptor;
111 write to the character string
117 dynamically allocate a new string with
120 These functions write the output under the control of a
122 string that specifies how subsequent arguments
123 (or arguments accessed via the variable-length argument facilities of
125 are converted for output.
127 These functions return the number of characters printed
128 (not including the trailing
130 used to end output to strings) or a negative value if an output error occurs,
135 which return the number of characters that would have been printed if the
138 (again, not including the final
148 to be a pointer to a buffer sufficiently large to hold the formatted string.
149 This pointer should be passed to
151 to release the allocated storage when it is no longer needed.
152 If sufficient space cannot be allocated,
156 will return \-1 and set
169 of the characters printed into the output string
172 character then gets the terminating
174 if the return value is greater than or equal to the
176 argument, the string was too short
177 and some of the printed characters were discarded.
178 The output is always null-terminated.
185 effectively assume an infinite
188 The format string is composed of zero or more directives:
193 which are copied unchanged to the output stream;
194 and conversion specifications, each of which results
195 in fetching zero or more subsequent arguments.
196 Each conversion specification is introduced by
200 The arguments must correspond properly (after type promotion)
201 with the conversion specifier.
204 the following appear in sequence:
207 An optional field, consisting of a decimal digit string followed by a
209 specifying the next argument to access.
210 If this field is not provided, the argument following the last
211 argument accessed will be used.
212 Arguments are numbered starting at
214 If unaccessed arguments in the format string are interspersed with ones that
215 are accessed the results will be indeterminate.
217 Zero or more of the following flags:
218 .Bl -tag -width ".So \ Sc (space)"
220 The value should be converted to an
223 .Cm c , d , i , n , p , s ,
226 conversions, this option has no effect.
229 conversions, the precision of the number is increased to force the first
230 character of the output string to a zero.
235 conversions, a non-zero result has the string
241 conversions) prepended to it.
243 .Cm a , A , e , E , f , F , g ,
246 conversions, the result will always contain a decimal point, even if no
247 digits follow it (normally, a decimal point appears in the results of
248 those conversions only if a digit follows).
253 conversions, trailing zeros are not removed from the result as they
255 .It So Cm 0 Sc (zero)
257 For all conversions except
259 the converted value is padded on the left with zeros rather than blanks.
260 If a precision is given with a numeric conversion
261 .Cm ( d , i , o , u , i , x ,
268 A negative field width flag;
269 the converted value is to be left adjusted on the field boundary.
272 conversions, the converted value is padded on the right with blanks,
273 rather than on the left with blanks or zeros.
279 .It So "\ " Sc (space)
280 A blank should be left before a positive number
281 produced by a signed conversion
282 .Cm ( a , A , d , e , E , f , F , g , G ,
286 A sign must always be placed before a
287 number produced by a signed conversion.
290 overrides a space if both are used.
296 or the integral portion of a floating point conversion
300 should be grouped and separated by thousands using
301 the non-monetary separator returned by
305 An optional decimal digit string specifying a minimum field width.
306 If the converted value has fewer characters than the field width, it will
307 be padded with spaces on the left (or right, if the left-adjustment
308 flag has been given) to fill out
311 An optional precision, in the form of a period
314 optional digit string.
315 If the digit string is omitted, the precision is taken as zero.
316 This gives the minimum number of digits to appear for
317 .Cm d , i , o , u , x ,
320 conversions, the number of digits to appear after the decimal-point for
321 .Cm a , A , e , E , f ,
324 conversions, the maximum number of significant digits for
328 conversions, or the maximum number of characters to be printed from a
333 An optional length modifier, that specifies the size of the argument.
334 The following length modifiers are valid for the
335 .Cm d , i , n , o , u , x ,
339 .Bl -column ".Cm q Em (deprecated)" ".Vt signed char" ".Vt unsigned long long" ".Vt long long *"
340 .It Sy Modifier Ta Cm d , i Ta Cm o , u , x , X Ta Cm n
341 .It Cm hh Ta Vt "signed char" Ta Vt "unsigned char" Ta Vt "signed char *"
342 .It Cm h Ta Vt short Ta Vt "unsigned short" Ta Vt "short *"
343 .It Cm l No (ell) Ta Vt long Ta Vt "unsigned long" Ta Vt "long *"
344 .It Cm ll No (ell ell) Ta Vt "long long" Ta Vt "unsigned long long" Ta Vt "long long *"
345 .It Cm j Ta Vt intmax_t Ta Vt uintmax_t Ta Vt "intmax_t *"
346 .It Cm t Ta Vt ptrdiff_t Ta (see note) Ta Vt "ptrdiff_t *"
347 .It Cm z Ta (see note) Ta Vt size_t Ta (see note)
348 .It Cm q Em (deprecated) Ta Vt quad_t Ta Vt u_quad_t Ta Vt "quad_t *"
354 modifier, when applied to a
358 conversion, indicates that the argument is of an unsigned type
359 equivalent in size to a
363 modifier, when applied to a
367 conversion, indicates that the argument is of a signed type equivalent in
370 Similarly, when applied to an
372 conversion, it indicates that the argument is a pointer to a signed type
373 equivalent in size to a
376 The following length modifier is valid for the
377 .Cm a , A , e , E , f , F , g ,
381 .Bl -column ".Sy Modifier" ".Cm a , A , e , E , f , F , g , G"
382 .It Sy Modifier Ta Cm a , A , e , E , f , F , g , G
383 .It Cm l No (ell) Ta Vt double
384 (ignored, same behavior as without it)
385 .It Cm L Ta Vt "long double"
388 The following length modifier is valid for the
393 .Bl -column ".Sy Modifier" ".Vt wint_t" ".Vt wchar_t *"
394 .It Sy Modifier Ta Cm c Ta Cm s
395 .It Cm l No (ell) Ta Vt wint_t Ta Vt "wchar_t *"
398 A character that specifies the type of conversion to be applied.
401 A field width or precision, or both, may be indicated by
404 or an asterisk followed by one or more decimal digits and a
410 argument supplies the field width or precision.
411 A negative field width is treated as a left adjustment flag followed by a
412 positive field width; a negative precision is treated as though it were
414 If a single format directive mixes positional
416 and non-positional arguments, the results are undefined.
418 The conversion specifiers and their meanings are:
419 .Bl -tag -width ".Cm diouxX"
423 (or appropriate variant) argument is converted to signed decimal
431 or unsigned hexadecimal
440 conversions; the letters
445 The precision, if any, gives the minimum number of digits that must
446 appear; if the converted value requires fewer digits, it is padded on
451 argument is converted to signed decimal, unsigned octal, or unsigned
452 decimal, as if the format had been
457 These conversion characters are deprecated, and will eventually disappear.
461 argument is rounded and converted in the style
463 .Oo \- Oc Ar d Li \&. Ar ddd Li e \\*[Pm] Ar dd
465 where there is one digit before the
466 decimal-point character
467 and the number of digits after it is equal to the precision;
468 if the precision is missing,
469 it is taken as 6; if the precision is
470 zero, no decimal-point character appears.
473 conversion uses the letter
477 to introduce the exponent.
478 The exponent always contains at least two digits; if the value is zero,
482 .Cm a , A , e , E , f , F , g ,
485 conversions, positive and negative infinity are represented as
489 respectively when using the lowercase conversion character, and
493 respectively when using the uppercase conversion character.
494 Similarly, NaN is represented as
496 when using the lowercase conversion, and
498 when using the uppercase conversion.
502 argument is rounded and converted to decimal notation in the style
504 .Oo \- Oc Ar ddd Li \&. Ar ddd ,
506 where the number of digits after the decimal-point character
507 is equal to the precision specification.
508 If the precision is missing, it is taken as 6; if the precision is
509 explicitly zero, no decimal-point character appears.
510 If a decimal point appears, at least one digit appears before it.
514 argument is converted in style
525 The precision specifies the number of significant digits.
526 If the precision is missing, 6 digits are given; if the precision is zero,
530 is used if the exponent from its conversion is less than \-4 or greater than
531 or equal to the precision.
532 Trailing zeros are removed from the fractional part of the result; a
533 decimal point appears only if it is followed by at least one digit.
537 argument is rounded and converted to hexadecimal notation in the style
539 .Oo \- Oc Li 0x Ar h Li \&. Ar hhhp Oo \\*[Pm] Oc Ar d ,
541 where the number of digits after the hexadecimal-point character
542 is equal to the precision specification.
543 If the precision is missing, it is taken as enough to represent
544 the floating-point number exactly, and no rounding occurs.
545 If the precision is zero, no hexadecimal-point character appears.
548 is a literal character
550 and the exponent consists of a positive or negative sign
551 followed by a decimal number representing an exponent of 2.
554 conversion uses the prefix
562 to represent the hex digits, and the letter
566 to separate the mantissa and exponent.
568 Note that there may be multiple valid ways to represent floating-point
569 numbers in this hexadecimal format.
571 .Li 0x1.92p+1 , 0x3.24p+0 , 0x6.48p-1 ,
576 and later always prints finite non-zero numbers using
578 as the digit before the hexadecimal point.
579 Zeroes are always represented with a mantissa of 0 (preceded by a
581 if appropriate) and an exponent of
592 argument is converted to an
593 .Vt "unsigned char" ,
594 and the resulting character is written.
598 (ell) modifier is used, the
600 argument shall be converted to a
602 and the (potentially multi-byte) sequence representing the
603 single wide character is written, including any shift sequences.
604 If a shift sequence is used, the shift state is also restored
605 to the original state after the character.
615 argument is expected to be a pointer to an array of character type (pointer
617 Characters from the array are written up to (but not including)
621 if a precision is specified, no more than the number specified are
623 If a precision is given, no null character
624 need be present; if the precision is not specified, or is greater than
625 the size of the array, the array must contain a terminating
631 (ell) modifier is used, the
633 argument is expected to be a pointer to an array of wide characters
634 (pointer to a wide string).
635 For each wide character in the string, the (potentially multi-byte)
636 sequence representing the
637 wide character is written, including any shift sequences.
638 If any shift sequence is used, the shift state is also restored
639 to the original state after the string.
640 Wide characters from the array are written up to (but not including)
644 if a precision is specified, no more than the number of bytes specified are
645 written (including shift sequences).
646 Partial characters are never written.
647 If a precision is given, no null character
648 need be present; if the precision is not specified, or is greater than
649 the number of bytes required to render the multibyte representation of
650 the string, the array must contain a terminating wide
656 pointer argument is printed in hexadecimal (as if by
661 The number of characters written so far is stored into the
662 integer indicated by the
664 (or variant) pointer argument.
665 No argument is converted.
670 No argument is converted.
671 The complete conversion specification
677 character is defined in the program's locale (category
680 In no case does a non-existent or small field width cause truncation of
681 a numeric field; if the result of a conversion is wider than the field
683 field is expanded to contain the conversion result.
685 To print a date and time in the form
686 .Dq Li "Sunday, July 3, 10:02" ,
691 are pointers to strings:
692 .Bd -literal -offset indent
694 fprintf(stdout, "%s, %s %d, %.2d:%.2d\en",
695 weekday, month, day, hour, min);
699 to five decimal places:
700 .Bd -literal -offset indent
703 fprintf(stdout, "pi = %.5f\en", 4 * atan(1.0));
706 To allocate a 128 byte string and print into it:
707 .Bd -literal -offset indent
711 char *newfmt(const char *fmt, ...)
715 if ((p = malloc(128)) == NULL)
718 (void) vsnprintf(p, 128, fmt, ap);
723 .Sh SECURITY CONSIDERATIONS
728 functions are easily misused in a manner which enables malicious users
729 to arbitrarily change a running program's functionality through
730 a buffer overflow attack.
735 assume an infinitely long string,
736 callers must be careful not to overflow the actual space;
737 this is often hard to assure.
738 For safety, programmers should use the
744 foo(const char *arbitrary_string, const char *and_another)
750 * This first sprintf is bad behavior. Do not use sprintf!
752 sprintf(onstack, "%s, %s", arbitrary_string, and_another);
755 * The following two lines demonstrate better use of
758 snprintf(onstack, sizeof(onstack), "%s, %s", arbitrary_string,
768 family of functions are also easily misused in a manner
769 allowing malicious users to arbitrarily change a running program's
770 functionality by either causing the program
771 to print potentially sensitive data
772 .Dq "left on the stack" ,
773 or causing it to generate a memory fault or bus error
774 by dereferencing an invalid pointer.
777 can be used to write arbitrary data to potentially carefully-selected
779 Programmers are therefore strongly advised to never pass untrusted strings
782 argument, as an attacker can put format specifiers in the string
783 to mangle your stack,
784 leading to a possible security hole.
785 This holds true even if the string was built using a function like
787 as the resulting string may still contain user-supplied conversion specifiers
788 for later interpolation by
791 Always use the proper secure idiom:
793 .Dl "snprintf(buffer, sizeof(buffer), \*q%s\*q, string);"
795 Many application writers used the name
799 function was introduced in
801 so a prototype is not provided by default in order to avoid
802 compatibility problems.
803 Applications that wish to use the
805 function described herein should either request a strict
807 environment by defining the macro
809 to the value 200809 or greater, or by defining the macro
811 prior to the inclusion of
813 For compatibility with GNU libc, defining either
817 prior to the inclusion of
823 The conversion formats
828 are provided only for backward compatibility.
829 The effect of padding the
831 format with zeros (either by the
833 flag or by specifying a precision), and the benign effect (i.e., none)
840 conversions, as well as other
841 nonsensical combinations such as
843 are not standard; such combinations
846 In addition to the errors documented for the
850 family of functions may fail if:
853 An invalid wide character code was encountered.
855 Insufficient storage space is available.
864 Subject to the caveats noted in the
879 With the same reservation, the
896 first appeared in the
899 These were implemented by
900 .An Peter Wemm Aq peter@FreeBSD.org
903 but were later replaced with a different implementation
905 .An Todd C. Miller Aq Todd.Miller@courtesan.com
912 functions were added in
917 family of functions do not correctly handle multibyte characters in the