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 2008-12-19 "GNU" "Linux Programmer's Manual"
36 printf, fprintf, sprintf, snprintf, vprintf, vfprintf, vsprintf,
37 vsnprintf \- formatted output conversion
41 .BI "int printf(const char *" format ", ...);"
43 .BI "int fprintf(FILE *" stream ", const char *" format ", ...);"
45 .BI "int sprintf(char *" str ", const char *" format ", ...);"
47 .BI "int snprintf(char *" str ", size_t " size ", const char *" format ", ...);"
49 .B #include <stdarg.h>
51 .BI "int vprintf(const char *" format ", va_list " ap );
53 .BI "int vfprintf(FILE *" stream ", const char *" format ", va_list " ap );
55 .BI "int vsprintf(char *" str ", const char *" format ", va_list " ap );
57 .BI "int vsnprintf(char *" str ", size_t " size ", const char *" format \
61 Feature Test Macro Requirements for glibc (see
62 .BR feature_test_macros (7)):
68 _BSD_SOURCE || _XOPEN_SOURCE\ >=\ 500 || _ISOC99_SOURCE; or
74 family produce output according to a
83 the standard output stream;
87 write output to the given output
94 write to the character string
103 bytes (including the trailing null byte (\(aq\e0\(aq)) to
111 are equivalent to the functions
116 respectively, except that they are called with a
118 instead of a variable number of arguments.
119 These functions do not call the
122 Because they invoke the
126 is undefined after the call.
130 These eight functions write the output under the control of a
132 string that specifies how subsequent arguments (or arguments accessed via
133 the variable-length argument facilities of
135 are converted for output.
137 C99 and POSIX.1-2001 specify that the results are undefined if a call to
143 would cause copying to take place between objects that overlap
144 (e.g., if the target string array and one of the supplied input arguments
145 refer to the same buffer).
148 Upon successful return, these functions return the number of characters
149 printed (not including the
150 trailing \(aq\e0\(aq used to end output to strings).
156 do not write more than
158 bytes (including the trailing \(aq\e0\(aq).
159 If the output was truncated due to this limit then the return value
160 is the number of characters (not including the trailing \(aq\e0\(aq)
161 which would have been written to the final string if enough space
163 Thus, a return value of
165 or more means that the output was truncated.
166 (See also below under NOTES.)
168 If an output error is encountered, a negative value is returned.
169 .SS "Format of the format string"
170 The format string is a character string, beginning and ending
171 in its initial shift state, if any.
172 The format string is composed of zero or more directives: ordinary
175 which are copied unchanged to the output stream;
176 and conversion specifications, each of which results in fetching zero or
177 more subsequent arguments.
178 Each conversion specification is introduced by
182 .IR "conversion specifier" .
183 In between there may be (in this order) zero or more
190 .IR "length modifier" .
192 The arguments must correspond properly (after type promotion) with the
193 conversion specifier.
194 By default, the arguments are used in the order
195 given, where each \(aq*\(aq and each conversion specifier asks for the next
196 argument (and it is an error if insufficiently many arguments are given).
197 One can also specify explicitly which argument is taken,
198 at each place where an argument is required, by writing "%m$" instead
199 of \(aq%\(aq and "*m$" instead of \(aq*\(aq,
200 where the decimal integer m denotes
201 the position in the argument list of the desired argument, indexed starting
207 printf("%*d", width, num);
215 printf("%2$*1$d", width, num);
220 The second style allows repeated references to the
222 The C99 standard does not include the style using \(aq$\(aq,
223 which comes from the Single Unix Specification.
225 \(aq$\(aq is used, it must be used throughout for all conversions taking an
226 argument and all width and precision arguments, but it may be mixed
227 with "%%" formats which do not consume an argument.
229 gaps in the numbers of arguments specified using \(aq$\(aq; for example, if
230 arguments 1 and 3 are specified, argument 2 must also be specified
231 somewhere in the format string.
233 For some numeric conversions a radix character ("decimal point") or
234 thousands' grouping character is used.
235 The actual character used
240 uses \(aq.\(aq as radix character, and does not have a grouping character.
245 printf("%\(aq.2f", 1234567.89);
249 results in "1234567.89" in the POSIX locale, in "1234567,89" in the
250 nl_NL locale, and in "1.234.567,89" in the da_DK locale.
251 .SS "The flag characters"
252 The character % is followed by zero or more of the following flags:
255 The value should be converted to an "alternate form".
258 conversions, the first character of the output string is made zero
259 (by prefixing a 0 if it was not zero already).
264 conversions, a nonzero result has the string "0x" (or "0X" for
266 conversions) prepended to it.
277 conversions, the result will always contain a decimal point, even if no
278 digits follow it (normally, a decimal point appears in the results of those
279 conversions only if a digit follows).
284 conversions, trailing zeros are not removed from the result as they would
286 For other conversions, the result is undefined.
289 The value should be zero padded.
306 conversions, the converted value is padded on the left with zeros rather
312 flags both appear, the
315 If a precision is given with a numeric conversion
326 For other conversions, the behavior is undefined.
329 The converted value is to be left adjusted on the field boundary.
330 (The default is right justification.)
333 conversions, the converted value is padded on the right with blanks, rather
334 than on the left with blanks or zeros.
342 (a space) A blank should be left before a positive number
343 (or empty string) produced by a signed conversion.
346 A sign (+ or \-) should always be placed before a number produced by a signed
348 By default a sign is used only for negative numbers.
351 overrides a space if both are used.
353 The five flag characters above are defined in the C standard.
354 The SUSv2 specifies one further flag character.
357 For decimal conversion
365 the output is to be grouped with thousands' grouping characters
366 if the locale information indicates any.
367 Note that many versions of
369 cannot parse this option and will issue a warning.
371 include \fI%\(aqF\fP.
373 glibc 2.2 adds one further flag character.
376 For decimal integer conversion
380 the output uses the locale's alternative output digits, if any.
381 For example, since glibc 2.2.3 this will give Arabic-Indic digits
382 in the Persian ("fa_IR") locale.
383 .\" outdigits keyword in locale file
384 .SS "The field width"
385 An optional decimal digit string (with nonzero first digit) specifying
386 a minimum field width.
387 If the converted value has fewer characters
388 than the field width, it will be padded with spaces on the left
389 (or right, if the left-adjustment flag has been given).
390 Instead of a decimal digit string one may write "*" or "*m$"
391 (for some decimal integer \fIm\fP) to specify that the field width
392 is given in the next argument, or in the \fIm\fP-th argument, respectively,
393 which must be of type
395 A negative field width is taken as a \(aq\-\(aq flag followed by a
396 positive field width.
397 In no case does a nonexistent or small field width cause truncation of a
398 field; if the result of a conversion is wider than the field width, the
399 field is expanded to contain the conversion result.
401 An optional precision, in the form of a period (\(aq.\(aq) followed by an
402 optional decimal digit string.
403 Instead of a decimal digit string one may write "*" or "*m$"
404 (for some decimal integer m) to specify that the precision
405 is given in the next argument, or in the m-th argument, respectively,
406 which must be of type
408 If the precision is given as just \(aq.\(aq, or the precision is negative,
409 the precision is taken to be zero.
410 This gives the minimum number of digits to appear for
418 conversions, the number of digits to appear after the radix character for
426 conversions, the maximum number of significant digits for
430 conversions, or the maximum number of characters to be printed from a
436 .SS "The length modifier"
437 Here, "integer conversion" stands for
448 A following integer conversion corresponds to a
452 argument, or a following
454 conversion corresponds to a pointer to a
459 A following integer conversion corresponds to a
462 .I unsigned short int
463 argument, or a following
465 conversion corresponds to a pointer to a
470 (ell) A following integer conversion corresponds to a
474 argument, or a following
476 conversion corresponds to a pointer to a
478 argument, or a following
480 conversion corresponds to a
482 argument, or a following
484 conversion corresponds to a pointer to
490 A following integer conversion corresponds to a
493 .I unsigned long long int
494 argument, or a following
496 conversion corresponds to a pointer to a
511 conversion corresponds to a
514 (C99 allows %LF, but SUSv2 does not.)
517 ("quad". 4.4BSD and Linux libc5 only.
519 This is a synonym for
523 A following integer conversion corresponds to an
530 A following integer conversion corresponds to a
541 A following integer conversion corresponds to a
545 The SUSv2 only knows about the length modifiers
573 .SS "The conversion specifier"
574 A character that specifies the type of conversion to be applied.
575 The conversion specifiers and their meanings are:
580 argument is converted to signed decimal notation.
581 The precision, if any, gives the minimum number of digits
582 that must appear; if the converted value requires fewer digits, it is
583 padded on the left with zeros.
584 The default precision is 1.
585 When 0 is printed with an explicit precision 0, the output is empty.
587 .BR o ", " u ", " x ", " X
590 argument is converted to unsigned octal
594 or unsigned hexadecimal
603 conversions; the letters
608 The precision, if any, gives the minimum number of digits
609 that must appear; if the converted value requires fewer digits, it is
610 padded on the left with zeros.
611 The default precision is 1.
612 When 0 is printed with an explicit precision 0, the output is empty.
617 argument is rounded and converted in the style
618 .if \w'\*(Pm'=0 .ds Pm \(+-
619 .RB [\-]d \&. ddd e \\*(Pmdd
620 where there is one digit before the decimal-point character and the number
621 of digits after it is equal to the precision; if the precision is missing,
622 it is taken as 6; if the precision is zero, no decimal-point character
626 conversion uses the letter
630 to introduce the exponent.
631 The exponent always contains at least two
632 digits; if the value is zero, the exponent is 00.
637 argument is rounded and converted to decimal notation in the style
639 where the number of digits after the decimal-point character is equal to
640 the precision specification.
641 If the precision is missing, it is taken as
642 6; if the precision is explicitly zero, no decimal-point character appears.
643 If a decimal point appears, at least one digit appears before it.
645 (The SUSv2 does not know about
647 and says that character string representations for infinity and NaN
648 may be made available.
649 The C99 standard specifies "[\-]inf" or "[\-]infinity"
650 for infinity, and a string starting with "nan" for NaN, in the case of
652 conversion, and "[\-]INF" or "[\-]INFINITY" or "NAN*" in the case of
659 argument is converted in style
670 The precision specifies the number of significant digits.
671 If the precision is missing, 6 digits are given; if the precision is zero,
675 is used if the exponent from its conversion is less than \-4 or greater
676 than or equal to the precision.
677 Trailing zeros are removed from the
678 fractional part of the result; a decimal point appears only if it is
679 followed by at least one digit.
682 (C99; not in SUSv2) For
686 argument is converted to hexadecimal notation (using the letters abcdef)
688 .RB [\-] 0x h \&. hhhh p \\*(Pmd;
691 conversion the prefix
693 the letters ABCDEF, and the exponent separator
696 There is one hexadecimal digit before the decimal point,
697 and the number of digits after it is equal to the precision.
698 The default precision suffices for an exact representation of the value
699 if an exact representation in base 2 exists
700 and otherwise is sufficiently large to distinguish values of type
702 The digit before the decimal point is unspecified for nonnormalized
703 numbers, and nonzero but otherwise unspecified for normalized numbers.
708 modifier is present, the
710 argument is converted to an
711 .IR "unsigned char" ,
712 and the resulting character is written.
715 modifier is present, the
717 (wide character) argument is converted to a multibyte sequence by a call
720 function, with a conversion state starting in the initial state, and the
721 resulting multibyte string is written.
726 modifier is present: The
728 argument is expected to be a pointer to an array of character type (pointer
730 Characters from the array are written up to (but not
731 including) a terminating null byte (\(aq\\0\(aq);
732 if a precision is specified, no more than the number specified
734 If a precision is given, no null byte need be present;
735 if the precision is not specified, or is greater than the size of the
736 array, the array must contain a terminating null byte.
740 modifier is present: The
742 argument is expected to be a pointer to an array of wide characters.
743 Wide characters from the array are converted to multibyte characters
744 (each by a call to the
746 function, with a conversion state starting in the initial state before
747 the first wide character), up to and including a terminating null
749 The resulting multibyte characters are written up to
750 (but not including) the terminating null byte.
752 specified, no more bytes than the number specified are written, but
753 no partial multibyte characters are written.
754 Note that the precision
755 determines the number of
757 written, not the number of
760 .IR "screen positions" .
761 The array must contain a terminating null wide character, unless a
762 precision is given and it is so small that the number of bytes written
763 exceeds it before the end of the array is reached.
766 (Not in C99, but in SUSv2.)
772 (Not in C99, but in SUSv2.)
780 pointer argument is printed in hexadecimal (as if by
786 The number of characters written so far is stored into the integer
789 (or variant) pointer argument.
790 No argument is converted.
795 .IR strerror(errno) .
796 No argument is required.
799 A \(aq%\(aq is written.
800 No argument is converted.
801 The complete conversion
802 specification is \(aq%%\(aq.
812 functions conform to C89 and C99.
817 functions conform to C99.
819 Concerning the return value of
821 SUSv2 and C99 contradict each other: when
825 then SUSv2 stipulates an unspecified return value less than 1,
828 to be NULL in this case, and gives the return value (as always)
829 as the number of characters that would have been written in case
830 the output string has been large enough.
832 Linux libc4 knows about the five C standard flags.
833 It knows about the length modifiers \fBh\fP, \fBl\fP, \fBL\fP,
835 \fBc\fP, \fBd\fP, \fBe\fP, \fBE\fP, \fBf\fP, \fBF\fP,
836 \fBg\fP, \fBG\fP, \fBi\fP, \fBn\fP, \fBo\fP, \fBp\fP,
837 \fBs\fP, \fBu\fP, \fBx\fP, and \fBX\fP,
838 where \fBF\fP is a synonym for \fBf\fP.
839 Additionally, it accepts \fBD\fP, \fBO\fP, and \fBU\fP as synonyms
840 for \fBld\fP, \fBlo\fP, and \fBlu\fP.
841 (This is bad, and caused serious bugs later, when
842 support for \fB%D\fP disappeared.)
843 No locale-dependent radix character,
844 no thousands' separator, no NaN or infinity, no "%m$" and "*m$".
846 Linux libc5 knows about the five C standard flags and the \(aq flag,
847 locale, "%m$" and "*m$".
848 It knows about the length modifiers \fBh\fP, \fBl\fP, \fBL\fP,
849 \fBZ\fP, and \fBq\fP, but accepts \fBL\fP and \fBq\fP
850 both for \fIlong double\fP and for \fIlong long int\fP (this is a bug).
851 It no longer recognizes \fBF\fP, \fBD\fP, \fBO\fP, and \fBU\fP,
852 but adds the conversion character
855 .IR strerror(errno) .
857 glibc 2.0 adds conversion characters \fBC\fP and \fBS\fP.
859 glibc 2.1 adds length modifiers \fBhh\fP, \fBj\fP, \fBt\fP, and \fBz\fP
860 and conversion characters \fBa\fP and \fBA\fP.
862 glibc 2.2 adds the conversion character \fBF\fP with C99 semantics,
863 and the flag character \fBI\fP.
865 Some programs imprudently rely on code such as the following
867 sprintf(buf, "%s some further text", buf);
871 However, the standards explicitly note that the results are undefined
872 if source and destination buffers overlap when calling
878 .\" http://sourceware.org/bugzilla/show_bug.cgi?id=7075
879 Depending on the version of
881 used, and the compiler options employed, calls such as the above will
883 produce the expected results.
885 The glibc implementation of the functions
889 conforms to the C99 standard, that is, behaves as described above,
890 since glibc version 2.1.
891 Until glibc 2.0.6 they would return \-1
892 when the output was truncated.
894 .\" Unix V7 defines the three routines
898 .\" and has the flag \-, the width or precision *, the length modifier l,
899 .\" and the conversions doxfegcsu, and also D,O,U,X as synonyms for ld,lo,lu,lx.
900 .\" This is still true for 2.9.1BSD, but 2.10BSD has the flags
901 .\" #, + and <space> and no longer mentions D,O,U,X.
906 .\" and warns not to use D,O,U,X.
907 .\" 4.3BSD Reno has the flag 0, the length modifiers h and L,
908 .\" and the conversions n, p, E, G, X (with current meaning)
909 .\" and deprecates D,O,U.
910 .\" 4.4BSD introduces the functions
913 .\" .BR vsnprintf (),
914 .\" and the length modifier q.
915 .\" FreeBSD also has functions
918 .\" .BR vasprintf (),
919 .\" that allocate a buffer large enough for
921 .\" In glibc there are functions
925 .\" that print to a file descriptor instead of a stream.
931 assume an arbitrarily long string, callers must be careful not to overflow
932 the actual space; this is often impossible to assure.
934 of the strings produced is locale-dependent and difficult to predict.
944 Linux libc4.[45] does not have a
946 but provides a libbsd that contains an
950 that is, one that ignores the
955 with early libc4 leads to serious security problems.
959 often indicates a bug, since
961 may contain a % character.
964 comes from untrusted user input, it may contain \fB%n\fP, causing the
966 call to write to memory and creating a security hole.
968 .\" Some floating-point conversions under early libc4
969 .\" caused memory leaks.
971 .if \w'\*(Pi'=0 .ds Pi pi
972 To print \*(Pi to five decimal places:
978 fprintf(stdout, "pi = %.5f\en", 4 * atan(1.0));
982 To print a date and time in the form "Sunday, July 3, 10:02",
987 are pointers to strings:
992 fprintf(stdout, "%s, %s %d, %.2d:%.2d\en",
993 weekday, month, day, hour, min);
997 Many countries use the day-month-year order.
998 Hence, an internationalized version must be able to print
999 the arguments in an order specified by the format:
1004 fprintf(stdout, format,
1005 weekday, month, day, hour, min);
1011 depends on locale, and may permute the arguments.
1016 "%1$s, %3$d. %2$s, %4$d:%5$.2d\en"
1020 one might obtain "Sonntag, 3. Juli, 10:02".
1022 To allocate a sufficiently large string and print into it
1023 (code correct for both glibc 2.0 and glibc 2.1):
1031 make_message(const char *fmt, ...)
1033 /* Guess we need no more than 100 bytes. */
1038 if ((p = malloc(size)) == NULL)
1042 /* Try to print in the allocated space. */
1044 n = vsnprintf(p, size, fmt, ap);
1046 /* If that worked, return the string. */
1047 if (n > \-1 && n < size)
1049 /* Else try again with more space. */
1050 if (n > \-1) /* glibc 2.1 */
1051 size = n+1; /* precisely what is needed */
1052 else /* glibc 2.0 */
1053 size *= 2; /* twice the old size */
1054 if ((np = realloc (p, size)) == NULL) {