1 .\" Copyright (c) 1999 Andries Brouwer (aeb@cwi.nl)
3 .\" This is free documentation; you can redistribute it and/or
4 .\" modify it under the terms of the GNU General Public License as
5 .\" published by the Free Software Foundation; either version 2 of
6 .\" the License, or (at your option) any later version.
8 .\" The GNU General Public License's references to "object code"
9 .\" and "executables" are to be interpreted as the output of any
10 .\" document formatting or typesetting system, including
11 .\" intermediate and printed output.
13 .\" This manual is distributed in the hope that it will be useful,
14 .\" but WITHOUT ANY WARRANTY; without even the implied warranty of
15 .\" MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
16 .\" GNU General Public License for more details.
18 .\" You should have received a copy of the GNU General Public
19 .\" License along with this manual; if not, write to the Free
20 .\" Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111,
24 .\" Earlier versions of this page influenced the present text.
25 .\" It was derived from a Berkeley page with version
26 .\" @(#)printf.3 6.14 (Berkeley) 7/30/91
27 .\" converted for Linux by faith@cs.unc.edu, updated by
28 .\" Helmut.Geyer@iwr.uni-heidelberg.de, agulbra@troll.no and Bruno Haible.
30 .\" 1999-11-25 aeb - Rewritten, using SUSv2 and C99.
31 .\" 2000-07-26 jsm28@hermes.cam.ac.uk - three small fixes
32 .\" 2000-10-16 jsm28@hermes.cam.ac.uk - more fixes
34 .TH PRINTF 3 2007-07-26 "GNU" "Linux Programmer's Manual"
36 printf, fprintf, sprintf, snprintf, vprintf, vfprintf, vsprintf, vsnprintf \- formatted output conversion
40 .BI "int printf(const char *" format ", ...);"
42 .BI "int fprintf(FILE *" stream ", const char *" format ", ...);"
44 .BI "int sprintf(char *" str ", const char *" format ", ...);"
46 .BI "int snprintf(char *" str ", size_t " size ", const char *" format ", ...);"
48 .B #include <stdarg.h>
50 .BI "int vprintf(const char *" format ", va_list " ap );
52 .BI "int vfprintf(FILE *" stream ", const char *" format ", va_list " ap );
54 .BI "int vsprintf(char *" str ", const char *" format ", va_list " ap );
56 .BI "int vsnprintf(char *" str ", size_t " size ", const char *" format ", va_list " ap );
60 Feature Test Macro Requirements for glibc (see
61 .BR feature_test_macros (7)):
67 _BSD_SOURCE || _XOPEN_SOURCE\ >=\ 500 || _ISOC99_SOURCE; or
73 family produce output according to a
82 the standard output stream;
86 write output to the given output
93 write to the character string
102 bytes (including the trailing null byte ('\e0')) to
110 are equivalent to the functions
115 respectively, except that they are called with a va_list instead
116 of a variable number of arguments.
117 These functions do not call the
120 Consequently, the value of
122 is undefined after the call.
123 The application should call
127 These eight functions write the output under the control of a
129 string that specifies how subsequent arguments (or arguments accessed via
130 the variable-length argument facilities of
132 are converted for output.
134 Upon successful return, these functions return the number of characters
135 printed (not including the trailing '\e0' used to end output to strings).
141 do not write more than
143 bytes (including the trailing '\e0').
144 If the output was truncated due to this limit then the return value
145 is the number of characters (not including the trailing '\e0')
146 which would have been written to the final string if enough space
148 Thus, a return value of
150 or more means that the output was truncated.
151 (See also below under NOTES.)
153 If an output error is encountered, a negative value is returned.
154 .SS "Format of the format string"
155 The format string is a character string, beginning and ending
156 in its initial shift state, if any.
157 The format string is composed of zero or more directives: ordinary
160 which are copied unchanged to the output stream;
161 and conversion specifications, each of which results in fetching zero or
162 more subsequent arguments.
163 Each conversion specification is introduced by
167 .IR "conversion specifier" .
168 In between there may be (in this order) zero or more
175 .IR "length modifier" .
177 The arguments must correspond properly (after type promotion) with the
178 conversion specifier.
179 By default, the arguments are used in the order
180 given, where each `*' and each conversion specifier asks for the next
181 argument (and it is an error if insufficiently many arguments are given).
182 One can also specify explicitly which argument is taken,
183 at each place where an argument is required, by writing `%m$' instead
184 of `%' and `*m$' instead of `*', where the decimal integer m denotes
185 the position in the argument list of the desired argument, indexed starting
191 printf("%*d", width, num);
199 printf("%2$*1$d", width, num);
204 The second style allows repeated references to the
206 The C99 standard does not include the style using `$',
207 which comes from the Single Unix Specification.
209 `$' is used, it must be used throughout for all conversions taking an
210 argument and all width and precision arguments, but it may be mixed
211 with `%%' formats which do not consume an argument.
213 gaps in the numbers of arguments specified using `$'; for example, if
214 arguments 1 and 3 are specified, argument 2 must also be specified
215 somewhere in the format string.
217 For some numeric conversions a radix character (`decimal point') or
218 thousands' grouping character is used.
219 The actual character used
224 uses `.' as radix character, and does not have a grouping character.
228 printf("%'.2f", 1234567.89);
231 results in `1234567.89' in the POSIX locale, in `1234567,89' in the
232 nl_NL locale, and in `1.234.567,89' in the da_DK locale.
233 .SS "The flag characters"
234 The character % is followed by zero or more of the following flags:
237 The value should be converted to an ``alternate form''.
240 conversions, the first character of the output string is made zero
241 (by prefixing a 0 if it was not zero already).
246 conversions, a non-zero result has the string `0x' (or `0X' for
248 conversions) prepended to it.
259 conversions, the result will always contain a decimal point, even if no
260 digits follow it (normally, a decimal point appears in the results of those
261 conversions only if a digit follows).
266 conversions, trailing zeros are not removed from the result as they would
268 For other conversions, the result is undefined.
271 The value should be zero padded.
288 conversions, the converted value is padded on the left with zeros rather
294 flags both appear, the
297 If a precision is given with a numeric conversion
308 For other conversions, the behavior is undefined.
311 The converted value is to be left adjusted on the field boundary.
312 (The default is right justification.)
315 conversions, the converted value is padded on the right with blanks, rather
316 than on the left with blanks or zeros.
324 (a space) A blank should be left before a positive number
325 (or empty string) produced by a signed conversion.
328 A sign (+ or \-) should always be placed before a number produced by a signed
330 By default a sign is used only for negative numbers.
333 overrides a space if both are used.
335 The five flag characters above are defined in the C standard.
336 The SUSv2 specifies one further flag character.
339 For decimal conversion
347 the output is to be grouped with thousands' grouping characters
348 if the locale information indicates any.
349 Note that many versions of
351 cannot parse this option and will issue a warning.
355 glibc 2.2 adds one further flag character.
358 For decimal integer conversion
362 the output uses the locale's alternative output digits, if any.
363 For example, since glibc 2.2.3 this will give Arabic-Indic digits
364 in the Persian (`fa_IR') locale.
365 .\" outdigits keyword in locale file
366 .SS "The field width"
367 An optional decimal digit string (with non-zero first digit) specifying
368 a minimum field width.
369 If the converted value has fewer characters
370 than the field width, it will be padded with spaces on the left
371 (or right, if the left-adjustment flag has been given).
372 Instead of a decimal digit string one may write `*' or `*m$'
373 (for some decimal integer m) to specify that the field width
374 is given in the next argument, or in the m-th argument, respectively,
375 which must be of type
377 A negative field width is taken as a `\-' flag followed by a
378 positive field width.
379 In no case does a non-existent or small field width cause truncation of a
380 field; if the result of a conversion is wider than the field width, the
381 field is expanded to contain the conversion result.
383 An optional precision, in the form of a period (`\&.') followed by an
384 optional decimal digit string.
385 Instead of a decimal digit string one may write `*' or `*m$'
386 (for some decimal integer m) to specify that the precision
387 is given in the next argument, or in the m-th argument, respectively,
388 which must be of type
390 If the precision is given as just `.', or the precision is negative,
391 the precision is taken to be zero.
392 This gives the minimum number of digits to appear for
400 conversions, the number of digits to appear after the radix character for
408 conversions, the maximum number of significant digits for
412 conversions, or the maximum number of characters to be printed from a
418 .SS "The length modifier"
419 Here, `integer conversion' stands for
430 A following integer conversion corresponds to a
434 argument, or a following
436 conversion corresponds to a pointer to a
441 A following integer conversion corresponds to a
444 .I unsigned short int
445 argument, or a following
447 conversion corresponds to a pointer to a
452 (ell) A following integer conversion corresponds to a
456 argument, or a following
458 conversion corresponds to a pointer to a
460 argument, or a following
462 conversion corresponds to a
464 argument, or a following
466 conversion corresponds to a pointer to
472 A following integer conversion corresponds to a
475 .I unsigned long long int
476 argument, or a following
478 conversion corresponds to a pointer to a
493 conversion corresponds to a
496 (C99 allows %LF, but SUSv2 does not.)
499 (`quad'. 4.4BSD and Linux libc5 only.
501 This is a synonym for
505 A following integer conversion corresponds to an
512 A following integer conversion corresponds to a
523 A following integer conversion corresponds to a
527 The SUSv2 only knows about the length modifiers
555 .SS "The conversion specifier"
556 A character that specifies the type of conversion to be applied.
557 The conversion specifiers and their meanings are:
562 argument is converted to signed decimal notation.
563 The precision, if any, gives the minimum number of digits
564 that must appear; if the converted value requires fewer digits, it is
565 padded on the left with zeros.
566 The default precision is 1.
567 When 0 is printed with an explicit precision 0, the output is empty.
572 argument is converted to unsigned octal
576 or unsigned hexadecimal
585 conversions; the letters
590 The precision, if any, gives the minimum number of digits
591 that must appear; if the converted value requires fewer digits, it is
592 padded on the left with zeros.
593 The default precision is 1.
594 When 0 is printed with an explicit precision 0, the output is empty.
599 argument is rounded and converted in the style
600 .if \w'\*(Pm'=0 .ds Pm \(+-
601 .BR "" [\-]d \&. ddd e \\*(Pmdd
602 where there is one digit before the decimal-point character and the number
603 of digits after it is equal to the precision; if the precision is missing,
604 it is taken as 6; if the precision is zero, no decimal-point character
608 conversion uses the letter
612 to introduce the exponent.
613 The exponent always contains at least two
614 digits; if the value is zero, the exponent is 00.
619 argument is rounded and converted to decimal notation in the style
620 .BR "" [\-]ddd \&. ddd,
621 where the number of digits after the decimal-point character is equal to
622 the precision specification.
623 If the precision is missing, it is taken as
624 6; if the precision is explicitly zero, no decimal-point character appears.
625 If a decimal point appears, at least one digit appears before it.
627 (The SUSv2 does not know about
629 and says that character string representations for infinity and NaN
630 may be made available.
631 The C99 standard specifies `[\-]inf' or `[\-]infinity'
632 for infinity, and a string starting with `nan' for NaN, in the case of
634 conversion, and `[\-]INF' or `[\-]INFINITY' or `NAN*' in the case of
641 argument is converted in style
652 The precision specifies the number of significant digits.
653 If the precision is missing, 6 digits are given; if the precision is zero,
657 is used if the exponent from its conversion is less than \-4 or greater
658 than or equal to the precision.
659 Trailing zeros are removed from the
660 fractional part of the result; a decimal point appears only if it is
661 followed by at least one digit.
664 (C99; not in SUSv2) For
668 argument is converted to hexadecimal notation (using the letters abcdef)
670 .BR "" [\-] 0x h \&. hhhh p \\*(Pmd;
673 conversion the prefix
675 the letters ABCDEF, and the exponent separator
678 There is one hexadecimal digit before the decimal point,
679 and the number of digits after it is equal to the precision.
680 The default precision suffices for an exact representation of the value
681 if an exact representation in base 2 exists
682 and otherwise is sufficiently large to distinguish values of type
684 The digit before the decimal point is unspecified for non-normalized
685 numbers, and non-zero but otherwise unspecified for normalized numbers.
690 modifier is present, the
692 argument is converted to an
693 .IR "unsigned char" ,
694 and the resulting character is written.
697 modifier is present, the
699 (wide character) argument is converted to a multibyte sequence by a call
702 function, with a conversion state starting in the initial state, and the
703 resulting multibyte string is written.
708 modifier is present: The
710 argument is expected to be a pointer to an array of character type (pointer
712 Characters from the array are written up to (but not
713 including) a terminating null byte ('\\0');
714 if a precision is specified, no more than the number specified
716 If a precision is given, no null byte need be present;
717 if the precision is not specified, or is greater than the size of the
718 array, the array must contain a terminating null byte.
722 modifier is present: The
724 argument is expected to be a pointer to an array of wide characters.
725 Wide characters from the array are converted to multibyte characters
726 (each by a call to the
728 function, with a conversion state starting in the initial state before
729 the first wide character), up to and including a terminating null
731 The resulting multibyte characters are written up to
732 (but not including) the terminating null byte.
734 specified, no more bytes than the number specified are written, but
735 no partial multibyte characters are written.
736 Note that the precision
737 determines the number of
739 written, not the number of
742 .IR "screen positions" .
743 The array must contain a terminating null wide character, unless a
744 precision is given and it is so small that the number of bytes written
745 exceeds it before the end of the array is reached.
748 (Not in C99, but in SUSv2.)
754 (Not in C99, but in SUSv2.)
762 pointer argument is printed in hexadecimal (as if by
768 The number of characters written so far is stored into the integer
771 (or variant) pointer argument.
772 No argument is converted.
777 .IR strerror(errno) .
778 No argument is required.
782 No argument is converted.
783 The complete conversion
784 specification is `%%'.
794 functions conform to C89 and C99.
799 functions conform to C99.
801 Concerning the return value of
803 SUSv2 and C99 contradict each other: when
807 then SUSv2 stipulates an unspecified return value less than 1,
810 to be NULL in this case, and gives the return value (as always)
811 as the number of characters that would have been written in case
812 the output string has been large enough.
814 Linux libc4 knows about the five C standard flags.
815 It knows about the length modifiers h,l,L, and the conversions
816 cdeEfFgGinopsuxX, where F is a synonym for f.
817 Additionally, it accepts D,O,U as synonyms for ld,lo,lu.
818 (This is bad, and caused serious bugs later, when
819 support for %D disappeared.)
820 No locale-dependent radix character,
821 no thousands' separator, no NaN or infinity, no %m$ and *m$.
823 Linux libc5 knows about the five C standard flags and the ' flag,
825 It knows about the length modifiers h,l,L,Z,q, but accepts L and q
826 both for \fIlong double\fP and for \fIlong long int\fP (this is a bug).
827 It no longer recognizes FDOU, but adds the conversion character
830 .IR strerror(errno) .
832 glibc 2.0 adds conversion characters C and S.
834 glibc 2.1 adds length modifiers hh,j,t,z and conversion characters a,A.
836 glibc 2.2 adds the conversion character F with C99 semantics, and the
839 The glibc implementation of the functions
843 conforms to the C99 standard, that is, behaves as described above,
844 since glibc version 2.1.
845 Until glibc 2.0.6 they would return \-1
846 when the output was truncated.
848 .\" Unix V7 defines the three routines
852 .\" and has the flag \-, the width or precision *, the length modifier l,
853 .\" and the conversions doxfegcsu, and also D,O,U,X as synonyms for ld,lo,lu,lx.
854 .\" This is still true for 2.9.1BSD, but 2.10BSD has the flags
855 .\" #, + and <space> and no longer mentions D,O,U,X.
860 .\" and warns not to use D,O,U,X.
861 .\" 4.3BSD Reno has the flag 0, the length modifiers h and L,
862 .\" and the conversions n, p, E, G, X (with current meaning)
863 .\" and deprecates D,O,U.
864 .\" 4.4BSD introduces the functions
867 .\" .BR vsnprintf (),
868 .\" and the length modifier q.
869 .\" FreeBSD also has functions
872 .\" .BR vasprintf (),
873 .\" that allocate a buffer large enough for
875 .\" In glibc there are functions
879 .\" that print to a file descriptor instead of a stream.
885 assume an arbitrarily long string, callers must be careful not to overflow
886 the actual space; this is often impossible to assure.
888 of the strings produced is locale-dependent and difficult to predict.
898 Linux libc4.[45] does not have a
900 but provides a libbsd that contains an
904 that is, one that ignores the
909 with early libc4 leads to serious security problems.
913 often indicates a bug, since
915 may contain a % character.
918 comes from untrusted user input, it may contain %n, causing the
920 call to write to memory and creating a security hole.
922 .\" Some floating point conversions under early libc4
923 .\" caused memory leaks.
926 .if \w'\*(Pi'=0 .ds Pi pi
927 To print \*(Pi to five decimal places:
933 fprintf(stdout, "pi = %.5f\en", 4 * atan(1.0));
937 To print a date and time in the form `Sunday, July 3, 10:02',
942 are pointers to strings:
947 fprintf(stdout, "%s, %s %d, %.2d:%.2d\en",
948 weekday, month, day, hour, min);
952 Many countries use the day-month-year order.
953 Hence, an internationalized version must be able to print
954 the arguments in an order specified by the format:
959 fprintf(stdout, format,
960 weekday, month, day, hour, min);
966 depends on locale, and may permute the arguments.
970 "%1$s, %3$d. %2$s, %4$d:%5$.2d\en"
973 one might obtain `Sonntag, 3. Juli, 10:02'.
975 To allocate a sufficiently large string and print into it
976 (code correct for both glibc 2.0 and glibc 2.1):
985 make_message(const char *fmt, ...)
987 /* Guess we need no more than 100 bytes. */
992 if ((p = malloc(size)) == NULL)
996 /* Try to print in the allocated space. */
998 n = vsnprintf(p, size, fmt, ap);
1000 /* If that worked, return the string. */
1001 if (n > \-1 && n < size)
1003 /* Else try again with more space. */
1004 if (n > \-1) /* glibc 2.1 */
1005 size = n+1; /* precisely what is needed */
1006 else /* glibc 2.0 */
1007 size *= 2; /* twice the old size */
1008 if ((np = realloc (p, size)) == NULL) {