1PRINTF(3) Linux Programmer's Manual PRINTF(3)
2
3
4
6 printf, fprintf, sprintf, snprintf, vprintf, vfprintf, vsprintf,
7 vsnprintf - formatted output conversion
8
10 #include <stdio.h>
11
12 int printf(const char *format, ...);
13 int fprintf(FILE *stream, const char *format, ...);
14 int sprintf(char *str, const char *format, ...);
15 int snprintf(char *str, size_t size, const char *format, ...);
16
17 #include <stdarg.h>
18
19 int vprintf(const char *format, va_list ap);
20 int vfprintf(FILE *stream, const char *format, va_list ap);
21 int vsprintf(char *str, const char *format, va_list ap);
22 int vsnprintf(char *str, size_t size, const char *format, va_list ap);
23
24 Feature Test Macro Requirements for glibc (see feature_test_macros(7)):
25
26 snprintf(), vsnprintf(): _BSD_SOURCE || _XOPEN_SOURCE >= 500 ||
27 _ISOC99_SOURCE; or cc -std=c99
28
30 The functions in the printf() family produce output according to a for‐
31 mat as described below. The functions printf() and vprintf() write
32 output to stdout, the standard output stream; fprintf() and vfprintf()
33 write output to the given output stream; sprintf(), snprintf(),
34 vsprintf() and vsnprintf() write to the character string str.
35
36 The functions snprintf() and vsnprintf() write at most size bytes
37 (including the trailing null byte ('\0')) to str.
38
39 The functions vprintf(), vfprintf(), vsprintf(), vsnprintf() are equiv‐
40 alent to the functions printf(), fprintf(), sprintf(), snprintf(),
41 respectively, except that they are called with a va_list instead of a
42 variable number of arguments. These functions do not call the va_end
43 macro. Because they invoke the va_arg macro, the value of ap is unde‐
44 fined after the call. See stdarg(3).
45
46 These eight functions write the output under the control of a format
47 string that specifies how subsequent arguments (or arguments accessed
48 via the variable-length argument facilities of stdarg(3)) are converted
49 for output.
50
51 C99 and POSIX.1-2001 specify that the results are undefined if a call
52 to sprintf(), snprintf(), vsprintf(), or vsnprintf() would cause to
53 copying to take place between objects that overlap (e.g., if the target
54 string array and one of the supplied input arguments refer to the same
55 buffer). See NOTES.
56
57 Return value
58 Upon successful return, these functions return the number of characters
59 printed (not including the trailing '\0' used to end output to
60 strings).
61
62 The functions snprintf() and vsnprintf() do not write more than size
63 bytes (including the trailing '\0'). If the output was truncated due
64 to this limit then the return value is the number of characters (not
65 including the trailing '\0') which would have been written to the final
66 string if enough space had been available. Thus, a return value of
67 size or more means that the output was truncated. (See also below
68 under NOTES.)
69
70 If an output error is encountered, a negative value is returned.
71
72 Format of the format string
73 The format string is a character string, beginning and ending in its
74 initial shift state, if any. The format string is composed of zero or
75 more directives: ordinary characters (not %), which are copied
76 unchanged to the output stream; and conversion specifications, each of
77 which results in fetching zero or more subsequent arguments. Each con‐
78 version specification is introduced by the character %, and ends with a
79 conversion specifier. In between there may be (in this order) zero or
80 more flags, an optional minimum field width, an optional precision and
81 an optional length modifier.
82
83 The arguments must correspond properly (after type promotion) with the
84 conversion specifier. By default, the arguments are used in the order
85 given, where each '*' and each conversion specifier asks for the next
86 argument (and it is an error if insufficiently many arguments are
87 given). One can also specify explicitly which argument is taken, at
88 each place where an argument is required, by writing "%m$" instead of
89 '%' and "*m$" instead of '*', where the decimal integer m denotes the
90 position in the argument list of the desired argument, indexed starting
91 from 1. Thus,
92
93 printf("%*d", width, num);
94
95 and
96
97 printf("%2$*1$d", width, num);
98
99 are equivalent. The second style allows repeated references to the
100 same argument. The C99 standard does not include the style using '$',
101 which comes from the Single Unix Specification. If the style using '$'
102 is used, it must be used throughout for all conversions taking an argu‐
103 ment and all width and precision arguments, but it may be mixed with
104 "%%" formats which do not consume an argument. There may be no gaps in
105 the numbers of arguments specified using '$'; for example, if arguments
106 1 and 3 are specified, argument 2 must also be specified somewhere in
107 the format string.
108
109 For some numeric conversions a radix character ("decimal point") or
110 thousands' grouping character is used. The actual character used
111 depends on the LC_NUMERIC part of the locale. The POSIX locale uses
112 '.' as radix character, and does not have a grouping character. Thus,
113
114 printf("%'.2f", 1234567.89);
115
116 results in "1234567.89" in the POSIX locale, in "1234567,89" in the
117 nl_NL locale, and in "1.234.567,89" in the da_DK locale.
118
119 The flag characters
120 The character % is followed by zero or more of the following flags:
121
122 # The value should be converted to an "alternate form". For o
123 conversions, the first character of the output string is made
124 zero (by prefixing a 0 if it was not zero already). For x and X
125 conversions, a non-zero result has the string "0x" (or "0X" for
126 X conversions) prepended to it. For a, A, e, E, f, F, g, and G
127 conversions, the result will always contain a decimal point,
128 even if no digits follow it (normally, a decimal point appears
129 in the results of those conversions only if a digit follows).
130 For g and G conversions, trailing zeros are not removed from the
131 result as they would otherwise be. For other conversions, the
132 result is undefined.
133
134 0 The value should be zero padded. For d, i, o, u, x, X, a, A, e,
135 E, f, F, g, and G conversions, the converted value is padded on
136 the left with zeros rather than blanks. If the 0 and - flags
137 both appear, the 0 flag is ignored. If a precision is given
138 with a numeric conversion (d, i, o, u, x, and X), the 0 flag is
139 ignored. For other conversions, the behavior is undefined.
140
141 - The converted value is to be left adjusted on the field bound‐
142 ary. (The default is right justification.) Except for n con‐
143 versions, the converted value is padded on the right with
144 blanks, rather than on the left with blanks or zeros. A - over‐
145 rides a 0 if both are given.
146
147 ' ' (a space) A blank should be left before a positive number (or
148 empty string) produced by a signed conversion.
149
150 + A sign (+ or -) should always be placed before a number produced
151 by a signed conversion. By default a sign is used only for neg‐
152 ative numbers. A + overrides a space if both are used.
153
154 The five flag characters above are defined in the C standard. The
155 SUSv2 specifies one further flag character.
156
157 ' For decimal conversion (i, d, u, f, F, g, G) the output is to be
158 grouped with thousands' grouping characters if the locale infor‐
159 mation indicates any. Note that many versions of gcc(1) cannot
160 parse this option and will issue a warning. SUSv2 does not
161 include %'F.
162
163 glibc 2.2 adds one further flag character.
164
165 I For decimal integer conversion (i, d, u) the output uses the
166 locale's alternative output digits, if any. For example, since
167 glibc 2.2.3 this will give Arabic-Indic digits in the Persian
168 ("fa_IR") locale.
169
170 The field width
171 An optional decimal digit string (with non-zero first digit) specifying
172 a minimum field width. If the converted value has fewer characters
173 than the field width, it will be padded with spaces on the left (or
174 right, if the left-adjustment flag has been given). Instead of a deci‐
175 mal digit string one may write "*" or "*m$" (for some decimal integer
176 m) to specify that the field width is given in the next argument, or in
177 the m-th argument, respectively, which must be of type int. A negative
178 field width is taken as a '-' flag followed by a positive field width.
179 In no case does a nonexistent or small field width cause truncation of
180 a field; if the result of a conversion is wider than the field width,
181 the field is expanded to contain the conversion result.
182
183 The precision
184 An optional precision, in the form of a period ('.') followed by an
185 optional decimal digit string. Instead of a decimal digit string one
186 may write "*" or "*m$" (for some decimal integer m) to specify that the
187 precision is given in the next argument, or in the m-th argument,
188 respectively, which must be of type int. If the precision is given as
189 just '.', or the precision is negative, the precision is taken to be
190 zero. This gives the minimum number of digits to appear for d, i, o,
191 u, x, and X conversions, the number of digits to appear after the radix
192 character for a, A, e, E, f, and F conversions, the maximum number of
193 significant digits for g and G conversions, or the maximum number of
194 characters to be printed from a string for s and S conversions.
195
196 The length modifier
197 Here, "integer conversion" stands for d, i, o, u, x, or X conversion.
198
199 hh A following integer conversion corresponds to a signed char or
200 unsigned char argument, or a following n conversion corresponds
201 to a pointer to a signed char argument.
202
203 h A following integer conversion corresponds to a short int or
204 unsigned short int argument, or a following n conversion corre‐
205 sponds to a pointer to a short int argument.
206
207 l (ell) A following integer conversion corresponds to a long int
208 or unsigned long int argument, or a following n conversion cor‐
209 responds to a pointer to a long int argument, or a following c
210 conversion corresponds to a wint_t argument, or a following s
211 conversion corresponds to a pointer to wchar_t argument.
212
213 ll (ell-ell). A following integer conversion corresponds to a long
214 long int or unsigned long long int argument, or a following n
215 conversion corresponds to a pointer to a long long int argument.
216
217 L A following a, A, e, E, f, F, g, or G conversion corresponds to
218 a long double argument. (C99 allows %LF, but SUSv2 does not.)
219
220 q ("quad". 4.4BSD and Linux libc5 only. Don't use.) This is a
221 synonym for ll.
222
223 j A following integer conversion corresponds to an intmax_t or
224 uintmax_t argument.
225
226 z A following integer conversion corresponds to a size_t or
227 ssize_t argument. (Linux libc5 has Z with this meaning. Don't
228 use it.)
229
230 t A following integer conversion corresponds to a ptrdiff_t argu‐
231 ment.
232
233 The SUSv2 only knows about the length modifiers h (in hd, hi, ho, hx,
234 hX, hn) and l (in ld, li, lo, lx, lX, ln, lc, ls) and L (in Le, LE, Lf,
235 Lg, LG).
236
237 The conversion specifier
238 A character that specifies the type of conversion to be applied. The
239 conversion specifiers and their meanings are:
240
241 d, i The int argument is converted to signed decimal notation. The
242 precision, if any, gives the minimum number of digits that must
243 appear; if the converted value requires fewer digits, it is
244 padded on the left with zeros. The default precision is 1.
245 When 0 is printed with an explicit precision 0, the output is
246 empty.
247
248 o, u, x, X
249 The unsigned int argument is converted to unsigned octal (o),
250 unsigned decimal (u), or unsigned hexadecimal (x and X) nota‐
251 tion. The letters abcdef are used for x conversions; the let‐
252 ters ABCDEF are used for X conversions. The precision, if any,
253 gives the minimum number of digits that must appear; if the con‐
254 verted value requires fewer digits, it is padded on the left
255 with zeros. The default precision is 1. When 0 is printed with
256 an explicit precision 0, the output is empty.
257
258 e, E The double argument is rounded and converted in the style
259 [-]d.ddde±dd where there is one digit before the decimal-point
260 character and the number of digits after it is equal to the pre‐
261 cision; if the precision is missing, it is taken as 6; if the
262 precision is zero, no decimal-point character appears. An E
263 conversion uses the letter E (rather than e) to introduce the
264 exponent. The exponent always contains at least two digits; if
265 the value is zero, the exponent is 00.
266
267 f, F The double argument is rounded and converted to decimal notation
268 in the style [-]ddd.ddd, where the number of digits after the
269 decimal-point character is equal to the precision specification.
270 If the precision is missing, it is taken as 6; if the precision
271 is explicitly zero, no decimal-point character appears. If a
272 decimal point appears, at least one digit appears before it.
273
274 (The SUSv2 does not know about F and says that character string
275 representations for infinity and NaN may be made available. The
276 C99 standard specifies "[-]inf" or "[-]infinity" for infinity,
277 and a string starting with "nan" for NaN, in the case of f con‐
278 version, and "[-]INF" or "[-]INFINITY" or "NAN*" in the case of
279 F conversion.)
280
281 g, G The double argument is converted in style f or e (or F or E for
282 G conversions). The precision specifies the number of signifi‐
283 cant digits. If the precision is missing, 6 digits are given;
284 if the precision is zero, it is treated as 1. Style e is used
285 if the exponent from its conversion is less than -4 or greater
286 than or equal to the precision. Trailing zeros are removed from
287 the fractional part of the result; a decimal point appears only
288 if it is followed by at least one digit.
289
290 a, A (C99; not in SUSv2) For a conversion, the double argument is
291 converted to hexadecimal notation (using the letters abcdef) in
292 the style [-]0xh.hhhhp±d; for A conversion the prefix 0X, the
293 letters ABCDEF, and the exponent separator P is used. There is
294 one hexadecimal digit before the decimal point, and the number
295 of digits after it is equal to the precision. The default pre‐
296 cision suffices for an exact representation of the value if an
297 exact representation in base 2 exists and otherwise is suffi‐
298 ciently large to distinguish values of type double. The digit
299 before the decimal point is unspecified for non-normalized num‐
300 bers, and non-zero but otherwise unspecified for normalized num‐
301 bers.
302
303 c If no l modifier is present, the int argument is converted to an
304 unsigned char, and the resulting character is written. If an l
305 modifier is present, the wint_t (wide character) argument is
306 converted to a multibyte sequence by a call to the wcrtomb(3)
307 function, with a conversion state starting in the initial state,
308 and the resulting multibyte string is written.
309
310 s If no l modifier is present: The const char * argument is
311 expected to be a pointer to an array of character type (pointer
312 to a string). Characters from the array are written up to (but
313 not including) a terminating null byte ('\0'); if a precision is
314 specified, no more than the number specified are written. If a
315 precision is given, no null byte need be present; if the preci‐
316 sion is not specified, or is greater than the size of the array,
317 the array must contain a terminating null byte.
318
319 If an l modifier is present: The const wchar_t * argument is
320 expected to be a pointer to an array of wide characters. Wide
321 characters from the array are converted to multibyte characters
322 (each by a call to the wcrtomb(3) function, with a conversion
323 state starting in the initial state before the first wide char‐
324 acter), up to and including a terminating null wide character.
325 The resulting multibyte characters are written up to (but not
326 including) the terminating null byte. If a precision is speci‐
327 fied, no more bytes than the number specified are written, but
328 no partial multibyte characters are written. Note that the pre‐
329 cision determines the number of bytes written, not the number of
330 wide characters or screen positions. The array must contain a
331 terminating null wide character, unless a precision is given and
332 it is so small that the number of bytes written exceeds it
333 before the end of the array is reached.
334
335 C (Not in C99, but in SUSv2.) Synonym for lc. Don't use.
336
337 S (Not in C99, but in SUSv2.) Synonym for ls. Don't use.
338
339 p The void * pointer argument is printed in hexadecimal (as if by
340 %#x or %#lx).
341
342 n The number of characters written so far is stored into the inte‐
343 ger indicated by the int * (or variant) pointer argument. No
344 argument is converted.
345
346 m (Glibc extension.) Print output of strerror(errno). No argu‐
347 ment is required.
348
349 % A '%' is written. No argument is converted. The complete con‐
350 version specification is '%%'.
351
353 The fprintf(), printf(), sprintf(), vprintf(), vfprintf(), and
354 vsprintf() functions conform to C89 and C99. The snprintf() and
355 vsnprintf() functions conform to C99.
356
357 Concerning the return value of snprintf(), SUSv2 and C99 contradict
358 each other: when snprintf() is called with size=0 then SUSv2 stipulates
359 an unspecified return value less than 1, while C99 allows str to be
360 NULL in this case, and gives the return value (as always) as the number
361 of characters that would have been written in case the output string
362 has been large enough.
363
364 Linux libc4 knows about the five C standard flags. It knows about the
365 length modifiers h, l, L, and the conversions c, d, e, E, f, F, g, G,
366 i, n, o, p, s, u, x, and X, where F is a synonym for f. Additionally,
367 it accepts D, O, and U as synonyms for ld, lo, and lu. (This is bad,
368 and caused serious bugs later, when support for %D disappeared.) No
369 locale-dependent radix character, no thousands' separator, no NaN or
370 infinity, no "%m$" and "*m$".
371
372 Linux libc5 knows about the five C standard flags and the ' flag,
373 locale, "%m$" and "*m$". It knows about the length modifiers h, l, L,
374 Z, and q, but accepts L and q both for long double and for long long
375 int (this is a bug). It no longer recognizes F, D, O, and U, but adds
376 the conversion character m, which outputs strerror(errno).
377
378 glibc 2.0 adds conversion characters C and S.
379
380 glibc 2.1 adds length modifiers hh, j, t, and z and conversion charac‐
381 ters a and A.
382
383 glibc 2.2 adds the conversion character F with C99 semantics, and the
384 flag character I.
385
387 Some programs imprudently rely on code such as the following
388
389 sprintf(buf, "%s some further text", buf);
390
391 to append text to buf. However, the standards explicitly note that the
392 results are undefined if source and destination buffers overlap when
393 calling sprintf(), snprintf(), vsprintf(), and vsnprintf(). Depending
394 on the version of gcc(1) used, and the compiler options employed, calls
395 such as the above will not produce the expected results.
396
397 The glibc implementation of the functions snprintf() and vsnprintf()
398 conforms to the C99 standard, that is, behaves as described above,
399 since glibc version 2.1. Until glibc 2.0.6 they would return -1 when
400 the output was truncated.
401
403 Because sprintf() and vsprintf() assume an arbitrarily long string,
404 callers must be careful not to overflow the actual space; this is often
405 impossible to assure. Note that the length of the strings produced is
406 locale-dependent and difficult to predict. Use snprintf() and
407 vsnprintf() instead (or asprintf(3) and vasprintf(3)).
408
409 Linux libc4.[45] does not have a snprintf(), but provides a libbsd that
410 contains an snprintf() equivalent to sprintf(), that is, one that
411 ignores the size argument. Thus, the use of snprintf() with early
412 libc4 leads to serious security problems.
413
414 Code such as printf(foo); often indicates a bug, since foo may contain
415 a % character. If foo comes from untrusted user input, it may contain
416 %n, causing the printf() call to write to memory and creating a secu‐
417 rity hole.
418
420 To print pi to five decimal places:
421
422 #include <math.h>
423 #include <stdio.h>
424 fprintf(stdout, "pi = %.5f\n", 4 * atan(1.0));
425
426 To print a date and time in the form "Sunday, July 3, 10:02", where
427 weekday and month are pointers to strings:
428
429 #include <stdio.h>
430 fprintf(stdout, "%s, %s %d, %.2d:%.2d\n",
431 weekday, month, day, hour, min);
432
433 Many countries use the day-month-year order. Hence, an international‐
434 ized version must be able to print the arguments in an order specified
435 by the format:
436
437 #include <stdio.h>
438 fprintf(stdout, format,
439 weekday, month, day, hour, min);
440
441 where format depends on locale, and may permute the arguments. With
442 the value:
443
444 "%1$s, %3$d. %2$s, %4$d:%5$.2d\n"
445
446 one might obtain "Sonntag, 3. Juli, 10:02".
447
448 To allocate a sufficiently large string and print into it (code correct
449 for both glibc 2.0 and glibc 2.1):
450
451 #include <stdio.h>
452 #include <stdlib.h>
453 #include <stdarg.h>
454
455 char *
456 make_message(const char *fmt, ...)
457 {
458 /* Guess we need no more than 100 bytes. */
459 int n, size = 100;
460 char *p, *np;
461 va_list ap;
462
463 if ((p = malloc(size)) == NULL)
464 return NULL;
465
466 while (1) {
467 /* Try to print in the allocated space. */
468 va_start(ap, fmt);
469 n = vsnprintf(p, size, fmt, ap);
470 va_end(ap);
471 /* If that worked, return the string. */
472 if (n > -1 && n < size)
473 return p;
474 /* Else try again with more space. */
475 if (n > -1) /* glibc 2.1 */
476 size = n+1; /* precisely what is needed */
477 else /* glibc 2.0 */
478 size *= 2; /* twice the old size */
479 if ((np = realloc (p, size)) == NULL) {
480 free(p);
481 return NULL;
482 } else {
483 p = np;
484 }
485 }
486 }
487
489 printf(1), asprintf(3), dprintf(3), scanf(3), setlocale(3), wcrtomb(3),
490 wprintf(3), locale(5)
491
493 This page is part of release 3.22 of the Linux man-pages project. A
494 description of the project, and information about reporting bugs, can
495 be found at http://www.kernel.org/doc/man-pages/.
496
497
498
499GNU 2008-12-19 PRINTF(3)