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