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