1 .\" $NetBSD: printf.3,v 1.63 2013/05/04 19:17:38 wiz Exp $
3 .\" Copyright (c) 1990, 1991, 1993
4 .\" The Regents of the University of California. All rights reserved.
6 .\" This code is derived from software contributed to Berkeley by
7 .\" Chris Torek and the American National Standards Committee X3,
8 .\" on Information Processing Systems.
10 .\" Redistribution and use in source and binary forms, with or without
11 .\" modification, are permitted provided that the following conditions
13 .\" 1. Redistributions of source code must retain the above copyright
14 .\" notice, this list of conditions and the following disclaimer.
15 .\" 2. Redistributions in binary form must reproduce the above copyright
16 .\" notice, this list of conditions and the following disclaimer in the
17 .\" documentation and/or other materials provided with the distribution.
18 .\" 3. Neither the name of the University nor the names of its contributors
19 .\" may be used to endorse or promote products derived from this software
20 .\" without specific prior written permission.
22 .\" THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
23 .\" ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
24 .\" IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
25 .\" ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
26 .\" FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
27 .\" DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
28 .\" OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
29 .\" HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
30 .\" LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
31 .\" OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
34 .\" @(#)printf.3 8.1 (Berkeley) 6/4/93
54 .Nd formatted output conversion
60 .Fn printf "const char * restrict format" ...
62 .Fn fprintf "FILE * restrict stream" "const char * restrict format" ...
64 .Fn dprintf "int fd" "const char * restrict format" ...
66 .Fn sprintf "char * restrict str" "const char * restrict format" ...
68 .Fn snprintf "char * restrict str" "size_t size" "const char * restrict format" ...
70 .Fn snprintf_ss "char * restrict str" "size_t size" "const char * restrict format" ...
72 .Fn asprintf "char ** restrict ret" "const char * restrict format" ...
75 .Fn vprintf "const char * restrict format" "va_list ap"
77 .Fn vfprintf "FILE * restrict stream" "const char * restrict format" "va_list ap"
79 .Fn vsprintf "char * restrict str" "const char * restrict format" "va_list ap"
81 .Fn vdprintf "int fd" "const char * restrict format" "va_list ap"
83 .Fn vsnprintf "char * restrict str" "size_t size" "const char * restrict format" "va_list ap"
85 .Fn vsnprintf_ss "char * restrict str" "size_t size" "const char * restrict format" "va_list ap"
87 .Fn vasprintf "char ** restrict ret" "const char * restrict format" "va_list ap"
91 family of functions produces output according to a
101 the standard output stream;
105 write output to the given output
110 write output to the given file descriptor
119 write to the character string
125 write to a dynamically allocated string that is stored in
128 These functions write the output under the control of a
130 string that specifies how subsequent arguments
131 (or arguments accessed via the variable-length argument facilities of
133 are converted for output.
138 are signal-safe standalone versions that do not handle
139 floating point formats, positional arguments, and wide characters.
144 return a pointer to a buffer sufficiently large to hold the
148 This pointer should be passed to
150 to release the allocated storage when it is no longer needed.
151 If sufficient space cannot be allocated, these functions
152 will return \-1 and set
157 Please note that these functions are not standardized, and not all
158 implementations can be assumed to set the
163 It is more portable to check for a return value of \-1 instead.
171 of the characters printed into the output string
174 character then gets the terminating
176 if the return value is greater than or equal to the
178 argument, the string was too short
179 and some of the printed characters were discarded.
182 is zero, nothing is written and
191 effectively assume an infinite
194 The format string is composed of zero or more directives:
199 which are copied unchanged to the output stream;
200 and conversion specifications, each of which results
201 in fetching zero or more subsequent arguments.
202 Each conversion specification is introduced by
205 The arguments must correspond properly (after type promotion)
206 with the conversion specifier.
209 the following appear in sequence:
212 An optional field, consisting of a decimal digit string followed by a
214 specifying the next argument to access.
215 If this field is not provided, the argument following the last
216 argument accessed will be used.
217 Arguments are numbered starting at
219 If unaccessed arguments in the format string are interspersed with ones that
220 are accessed the results will be indeterminate.
222 Zero or more of the following flags:
223 .Bl -tag -width ".So \ Sc (space)"
225 The value should be converted to an
236 conversions, this option has no effect.
239 conversions, the precision of the number is increased to force the first
240 character of the output string to a zero (except if a zero value is printed
241 with an explicit precision of zero).
246 conversions, a non-zero result has the string
252 conversions) prepended to it.
263 conversions, the result will always contain a decimal point, even if no
264 digits follow it (normally, a decimal point appears in the results of
265 those conversions only if a digit follows).
270 conversions, trailing zeros are not removed from the result as they
272 .It So Cm 0 Sc (zero)
274 For all conversions except
276 the converted value is padded on the left with zeros rather than blanks.
277 If a precision is given with a numeric conversion
290 A negative field width flag;
291 the converted value is to be left adjusted on the field boundary.
294 conversions, the converted value is padded on the right with blanks,
295 rather than on the left with blanks or zeros.
301 .It So "\ " Sc (space)
302 A blank should be left before a positive number
303 produced by a signed conversion
316 A sign must always be placed before a
317 number produced by a signed conversion.
320 overrides a space if both are used.
326 or the integral portion of a floating point conversion
330 should be grouped and separated by thousands using
331 the non-monetary separator returned by
335 An optional decimal digit string specifying a minimum field width.
336 If the converted value has fewer characters than the field width, it will
337 be padded with spaces on the left (or right, if the left-adjustment
338 flag has been given) to fill out the field width.
340 An optional precision, in the form of a period
342 followed by an optional digit string.
343 If the digit string is omitted, the precision is taken as zero.
344 This gives the minimum number of digits to appear for
352 conversions, the number of digits to appear after the decimal-point for
360 conversions, the maximum number of significant digits for
364 conversions, or the maximum number of characters to be printed from a
369 An optional length modifier, that specifies the size of the argument.
370 The following length modifiers are valid for the
371 .Cm d , i , n , o , u , x ,
375 .Bl -column ".Cm q Em (deprecated)" ".Vt signed char" ".Vt unsigned long long" ".Vt long long *"
376 .It Sy Modifier Ta Cm d , i Ta Cm o , u , x , X Ta Cm n
377 .It Cm hh Ta Vt "signed char" Ta Vt "unsigned char" Ta Vt "signed char *"
378 .It Cm h Ta Vt short Ta Vt "unsigned short" Ta Vt "short *"
379 .It Cm l No (ell) Ta Vt long Ta Vt "unsigned long" Ta Vt "long *"
380 .It Cm ll No (ell ell) Ta Vt "long long" Ta Vt "unsigned long long" Ta Vt "long long *"
381 .It Cm j Ta Vt intmax_t Ta Vt uintmax_t Ta Vt "intmax_t *"
382 .It Cm t Ta Vt ptrdiff_t Ta (see note) Ta Vt "ptrdiff_t *"
383 .It Cm z Ta (see note) Ta Vt size_t Ta (see note)
384 .It Cm q Em (deprecated) Ta Vt quad_t Ta Vt u_quad_t Ta Vt "quad_t *"
390 modifier, when applied to a
394 conversion, indicates that the argument is of an unsigned type
395 equivalent in size to a
399 modifier, when applied to a
403 conversion, indicates that the argument is of a signed type equivalent in
406 Similarly, when applied to an
408 conversion, it indicates that the argument is a pointer to a signed type
409 equivalent in size to a
413 if the standard integer types described in
415 are used, it is recommended that the predefined format string specifier
416 macros are used when possible.
417 These are further described in
420 The following length modifier is valid for the
431 .Bl -column ".Sy Modifier" ".Cm a , A , e , E , f , F , g , G"
432 .It Sy Modifier Ta Cm a , A , e , E , f , F , g , G
433 .It Cm l No (ell) Ta Vt double
434 (ignored, same behavior as without it)
435 .It Cm L Ta Vt "long double"
438 The following length modifier is valid for the
443 .Bl -column ".Sy Modifier" ".Vt wint_t" ".Vt wchar_t *"
444 .It Sy Modifier Ta Cm c Ta Cm s
445 .It Cm l No (ell) Ta Vt wint_t Ta Vt "wchar_t *"
448 A character that specifies the type of conversion to be applied.
451 A field width or precision, or both, may be indicated by
454 or an asterisk followed by one or more decimal digits and a
460 argument supplies the field width or precision.
461 A negative field width is treated as a left adjustment flag followed by a
462 positive field width; a negative precision is treated as though it were
464 If a single format directive mixes positional
466 and non-positional arguments, the results are undefined.
468 The conversion specifiers and their meanings are:
469 .Bl -tag -width ".Cm diouxX"
473 (or appropriate variant) argument is converted to signed decimal
481 or unsigned hexadecimal
490 conversions; the letters
495 The precision, if any, gives the minimum number of digits that must
496 appear; if the converted value requires fewer digits, it is padded on
501 argument is converted to signed decimal, unsigned octal, or unsigned
502 decimal, as if the format had been
508 These conversion characters are deprecated, and will eventually disappear.
512 argument is rounded and converted in the style
514 .Oo \- Oc Ar d Li \&. Ar ddd Li e \*[Pm] Ar dd
516 where there is one digit before the
517 decimal-point character
518 and the number of digits after it is equal to the precision;
519 if the precision is missing,
520 it is taken as 6; if the precision is
521 zero, no decimal-point character appears.
524 conversion uses the letter
528 to introduce the exponent.
529 The exponent always contains at least two digits; if the value is zero,
542 conversions, positive and negative infinity are represented as
546 respectively when using the lowercase conversion character, and
550 respectively when using the uppercase conversion character.
551 Similarly, NaN is represented as
553 when using the lowercase conversion, and
555 when using the uppercase conversion.
559 argument is rounded and converted to decimal notation in the style
561 .Oo \- Oc Ar ddd Li \&. Ar ddd ,
563 where the number of digits after the decimal-point character
564 is equal to the precision specification.
565 If the precision is missing, it is taken as 6; if the precision is
566 explicitly zero, no decimal-point character appears.
567 If a decimal point appears, at least one digit appears before it.
571 argument is converted in style
582 The precision specifies the number of significant digits.
583 If the precision is missing, 6 digits are given; if the precision is zero,
587 is used if the exponent from its conversion is less than \-4 or greater than
588 or equal to the precision.
589 Trailing zeros are removed from the fractional part of the result; a
590 decimal point appears only if it is followed by at least one digit.
594 argument is rounded and converted to hexadecimal notation in the style
596 .Oo \- Oc Li 0x Ar h Li \&. Ar hhhp Oo \*[Pm] Oc Ar d ,
598 where the number of digits after the hexadecimal-point character
599 is equal to the precision specification.
600 If the precision is missing, it is taken as enough to represent
601 the floating-point number exactly, and no rounding occurs.
602 If the precision is zero, no hexadecimal-point character appears.
605 is a literal character
607 and the exponent consists of a positive or negative sign
608 followed by a decimal number representing an exponent of 2.
611 conversion uses the prefix
619 to represent the hex digits, and the letter
623 to separate the mantissa and exponent.
625 Note that there may be multiple valid ways to represent floating-point
626 numbers in this hexadecimal format.
628 .Li 0x3.24p+0 , 0x6.48p-1
632 The format chosen depends on the internal representation of the
633 number, but the implementation guarantees that the length of the
634 mantissa will be minimized.
635 Zeroes are always represented with a mantissa of 0 (preceded by a
637 if appropriate) and an exponent of
648 argument is converted to an
649 .Vt "unsigned char" ,
650 and the resulting character is written.
654 (ell) modifier is used, the
656 argument shall be converted to a
658 and the (potentially multi-byte) sequence representing the
659 single wide character is written, including any shift sequences.
660 If a shift sequence is used, the shift state is also restored
661 to the original state after the character.
671 argument is expected to be a pointer to an array of character type (pointer
673 Characters from the array are written up to (but not including)
677 if a precision is specified, no more than the number specified are
679 If a precision is given, no null character
680 need be present; if the precision is not specified, or is greater than
681 the size of the array, the array must contain a terminating
687 (ell) modifier is used, the
689 argument is expected to be a pointer to an array of wide characters
690 (pointer to a wide string).
691 For each wide character in the string, the (potentially multi-byte)
692 sequence representing the
693 wide character is written, including any shift sequences.
694 If any shift sequence is used, the shift state is also restored
695 to the original state after the string.
696 Wide characters from the array are written up to (but not including)
700 if a precision is specified, no more than the number of bytes specified are
701 written (including shift sequences).
702 Partial characters are never written.
703 If a precision is given, no null character
704 need be present; if the precision is not specified, or is greater than
705 the number of bytes required to render the multibyte representation of
706 the string, the array must contain a terminating wide
712 pointer argument is printed in hexadecimal (as if by
717 The number of characters written so far is stored into the
718 integer indicated by the
720 (or variant) pointer argument.
721 No argument is converted.
726 No argument is converted.
727 The complete conversion specification is
732 character is defined in the program's locale (category
735 In no case does a non-existent or small field width cause truncation of
736 a numeric field; if the result of a conversion is wider than the field
738 field is expanded to contain the conversion result.
740 These functions return
741 the number of characters printed, or that would be printed if there
742 was adequate space in case of
747 (not including the trailing
749 used to end output to strings).
750 If an output error was encountered, these functions shall return a
753 To print a date and time in the form
754 .Dq Li "Sunday, July 3, 10:02" ,
759 are pointers to strings:
760 .Bd -literal -offset indent
761 #include \*[Lt]stdio.h\*[Gt]
762 fprintf(stdout, "%s, %s %d, %.2d:%.2d\en",
763 weekday, month, day, hour, min);
767 to five decimal places:
768 .Bd -literal -offset indent
769 #include \*[Lt]math.h\*[Gt]
770 #include \*[Lt]stdio.h\*[Gt]
771 fprintf(stdout, "pi = %.5f\en", 4 * atan(1.0));
774 To allocate a 128 byte string and print into it:
775 .Bd -literal -offset indent
776 #include \*[Lt]stdio.h\*[Gt]
777 #include \*[Lt]stdlib.h\*[Gt]
778 #include \*[Lt]stdarg.h\*[Gt]
779 char *newfmt(const char *fmt, ...)
783 if ((p = malloc(128)) == NULL)
786 (void) vsnprintf(p, 128, fmt, ap);
792 In addition to the errors documented for the
796 family of functions may fail if:
799 An invalid wide-character code was encountered.
801 Insufficient storage space is available.
811 Subject to the caveats noted in the
826 With the same reservation, the
843 are modeled on the ones that first appeared in the GNU C library.
846 is non-standard and appeared in
861 assume an infinitely long string, callers must be careful not to
862 overflow the actual space; this is often impossible to assure.
863 For safety, programmers should use the
867 family of interfaces instead.
870 interfaces are not available on older
873 interfaces are not yet portable.
875 It is important never to pass a string with user-supplied data as a
878 An attacker can put format specifiers in the string to mangle your stack,
879 leading to a possible security hole.
880 This holds true even if you have built the string
882 using a function like
884 as the resulting string may still contain user-supplied conversion specifiers
885 for later interpolation by
888 Be sure to use the proper secure idiom:
889 .Bd -literal -offset indent
890 snprintf(buffer, sizeof(buffer), "%s", string);
895 to know the size of each argument passed.
896 If you use positional arguments you must ensure that all parameters, up to the
897 last positionally specified parameter, are used in the format string.
898 This allows for the format string to be parsed for this information.
899 Failure to do this will mean your code is non-portable and liable to fail.
901 In this implementation, passing a
906 format specifier will output
909 Programs that depend on this behavior are non-portable and may crash
910 on other systems or in the future.
912 The conversion formats
917 are not standard and are provided only for backward compatibility.
918 The effect of padding the
920 format with zeros (either by the
922 flag or by specifying a precision), and the benign effect (i.e. none)
929 conversions, as well as other nonsensical combinations such as
931 are not standard; such combinations should be avoided.
935 family of functions do not correctly handle multibyte characters in the
938 .Sh SECURITY CONSIDERATIONS
943 functions are easily misused in a manner which enables malicious users
944 to arbitrarily change a running program's functionality through
945 a buffer overflow attack.
950 assume an infinitely long string,
951 callers must be careful not to overflow the actual space;
952 this is often hard to assure.
953 For safety, programmers should use the
959 foo(const char *arbitrary_string, const char *and_another)
965 * This first sprintf is bad behavior. Do not use sprintf!
967 sprintf(onstack, "%s, %s", arbitrary_string, and_another);
970 * The following two lines demonstrate better use of
973 snprintf(onstack, sizeof(onstack), "%s, %s", arbitrary_string,
983 family of functions are also easily misused in a manner
984 allowing malicious users to arbitrarily change a running program's
985 functionality by either causing the program
986 to print potentially sensitive data
987 .Dq "left on the stack" ,
988 or causing it to generate a memory fault or bus error
989 by dereferencing an invalid pointer.
992 can be used to write arbitrary data to potentially carefully-selected
994 Programmers are therefore strongly advised to never pass untrusted strings
997 argument, as an attacker can put format specifiers in the string
998 to mangle your stack,
999 leading to a possible security hole.
1000 This holds true even if the string was built using a function like
1002 as the resulting string may still contain user-supplied conversion specifiers
1003 for later interpolation by
1006 Always use the proper secure idiom:
1008 .Dl "snprintf(buffer, sizeof(buffer), \*q%s\*q, string);"