1PRINTF(3)                  Linux Programmer's Manual                 PRINTF(3)
2
3
4

NAME

6       printf,  fprintf,  dprintf,  sprintf,  snprintf, vprintf, vfprintf, vd‐
7       printf, vsprintf, vsnprintf - formatted output conversion
8

SYNOPSIS

10       #include <stdio.h>
11
12       int printf(const char *restrict format, ...);
13       int fprintf(FILE *restrict stream,
14                   const char *restrict format, ...);
15       int dprintf(int fd,
16                   const char *restrict format, ...);
17       int sprintf(char *restrict str,
18                   const char *restrict format, ...);
19       int snprintf(char *restrict str, size_t size,
20                   const char *restrict format, ...);
21
22       #include <stdarg.h>
23
24       int vprintf(const char *restrict format, va_list ap);
25       int vfprintf(FILE *restrict stream,
26                   const char *restrict format, va_list ap);
27       int vdprintf(int fd,
28                   const char *restrict format, va_list ap);
29       int vsprintf(char *restrict str,
30                   const char *restrict format, va_list ap);
31       int vsnprintf(char *restrict str, size_t size,
32                   const char *restrict format, va_list ap);
33
34   Feature Test Macro Requirements for glibc (see feature_test_macros(7)):
35
36       snprintf(), vsnprintf():
37           _XOPEN_SOURCE >= 500 || _ISOC99_SOURCE
38               || /* Glibc <= 2.19: */ _BSD_SOURCE
39
40       dprintf(), vdprintf():
41           Since glibc 2.10:
42               _POSIX_C_SOURCE >= 200809L
43           Before glibc 2.10:
44               _GNU_SOURCE
45

DESCRIPTION

47       The functions in the printf() family produce output according to a for‐
48       mat  as  described  below.   The functions printf() and vprintf() write
49       output to stdout, the standard output stream; fprintf() and  vfprintf()
50       write  output  to  the  given  output  stream;  sprintf(),  snprintf(),
51       vsprintf(), and vsnprintf() write to the character string str.
52
53       The function dprintf() is the same as fprintf() except that it  outputs
54       to a file descriptor, fd, instead of to a stdio(3) stream.
55
56       The  functions snprintf() and vsnprintf() write at most size bytes (in‐
57       cluding the terminating null byte ('\0')) to str.
58
59       The  functions  vprintf(),  vfprintf(),  vdprintf(),  vsprintf(),   vs‐
60       nprintf()   are   equivalent  to  the  functions  printf(),  fprintf(),
61       dprintf(), sprintf(), snprintf(), respectively, except  that  they  are
62       called with a va_list instead of a variable number of arguments.  These
63       functions do not call the va_end macro.  Because they invoke the va_arg
64       macro, the value of ap is undefined after the call.  See stdarg(3).
65
66       All  of  these functions write the output under the control of a format
67       string that specifies how subsequent arguments (or  arguments  accessed
68       via the variable-length argument facilities of stdarg(3)) are converted
69       for output.
70
71       C99 and POSIX.1-2001 specify that the results are undefined if  a  call
72       to  sprintf(), snprintf(), vsprintf(), or vsnprintf() would cause copy‐
73       ing to take place between objects that overlap  (e.g.,  if  the  target
74       string  array and one of the supplied input arguments refer to the same
75       buffer).  See NOTES.
76
77   Format of the format string
78       The format string is a character string, beginning and  ending  in  its
79       initial  shift state, if any.  The format string is composed of zero or
80       more directives: ordinary characters (not  %),  which  are  copied  un‐
81       changed  to  the  output stream; and conversion specifications, each of
82       which results in fetching zero or more subsequent arguments.  Each con‐
83       version specification is introduced by the character %, and ends with a
84       conversion specifier.  In between there may be (in this order) zero  or
85       more  flags, an optional minimum field width, an optional precision and
86       an optional length modifier.
87
88       The overall syntax of a conversion specification is:
89
90           %[$][flags][width][.precision][length modifier]conversion
91
92       The arguments must correspond properly (after type promotion) with  the
93       conversion  specifier.  By default, the arguments are used in the order
94       given, where each '*' (see Field width and Precision  below)  and  each
95       conversion  specifier asks for the next argument (and it is an error if
96       insufficiently many arguments are given).  One can also specify explic‐
97       itly  which  argument  is taken, at each place where an argument is re‐
98       quired, by writing "%m$" instead of '%' and "*m$" instead of '*', where
99       the  decimal integer m denotes the position in the argument list of the
100       desired argument, indexed starting from 1.  Thus,
101
102           printf("%*d", width, num);
103
104       and
105
106           printf("%2$*1$d", width, num);
107
108       are equivalent.  The second style allows  repeated  references  to  the
109       same  argument.  The C99 standard does not include the style using '$',
110       which comes from the Single UNIX Specification.  If the style using '$'
111       is used, it must be used throughout for all conversions taking an argu‐
112       ment and all width and precision arguments, but it may  be  mixed  with
113       "%%"  formats,  which do not consume an argument.  There may be no gaps
114       in the numbers of arguments specified using '$'; for example, if  argu‐
115       ments  1  and  3 are specified, argument 2 must also be specified some‐
116       where in the format string.
117
118       For some numeric conversions a radix  character  ("decimal  point")  or
119       thousands'  grouping  character is used.  The actual character used de‐
120       pends on the LC_NUMERIC part of the locale.  (See  setlocale(3).)   The
121       POSIX  locale uses '.' as radix character, and does not have a grouping
122       character.  Thus,
123
124           printf("%'.2f", 1234567.89);
125
126       results in "1234567.89" in the POSIX locale,  in  "1234567,89"  in  the
127       nl_NL locale, and in "1.234.567,89" in the da_DK locale.
128
129   Flag characters
130       The character % is followed by zero or more of the following flags:
131
132       #      The  value  should  be  converted to an "alternate form".  For o
133              conversions, the first character of the output  string  is  made
134              zero (by prefixing a 0 if it was not zero already).  For x and X
135              conversions, a nonzero result has the string "0x" (or "0X" for X
136              conversions)  prepended  to  it.  For a, A, e, E, f, F, g, and G
137              conversions, the result will always  contain  a  decimal  point,
138              even  if  no digits follow it (normally, a decimal point appears
139              in the results of those conversions only if  a  digit  follows).
140              For g and G conversions, trailing zeros are not removed from the
141              result as they would otherwise be.  For other  conversions,  the
142              result is undefined.
143
144       0      The value should be zero padded.  For d, i, o, u, x, X, a, A, e,
145              E, f, F, g, and G conversions, the converted value is padded  on
146              the  left  with  zeros rather than blanks.  If the 0 and - flags
147              both appear, the 0 flag is ignored.  If  a  precision  is  given
148              with  a numeric conversion (d, i, o, u, x, and X), the 0 flag is
149              ignored.  For other conversions, the behavior is undefined.
150
151       -      The converted value is to be left adjusted on the  field  bound‐
152              ary.  (The default is right justification.)  The converted value
153              is padded on the right with blanks, rather than on the left with
154              blanks or zeros.  A - overrides a 0 if both are given.
155
156       ' '    (a  space)  A  blank should be left before a positive number (or
157              empty string) produced by a signed conversion.
158
159       +      A sign (+ or -) should always be placed before a number produced
160              by  a  signed  conversion.   By default, a sign is used only for
161              negative numbers.  A + overrides a space if both are used.
162
163       The five flag characters above are defined in the  C99  standard.   The
164       Single UNIX Specification specifies one further flag character.
165
166       '      For decimal conversion (i, d, u, f, F, g, G) the output is to be
167              grouped with thousands' grouping characters if the locale infor‐
168              mation  indicates any.  (See setlocale(3).)  Note that many ver‐
169              sions of gcc(1) cannot parse this option and will issue a  warn‐
170              ing.  (SUSv2 did not include %'F, but SUSv3 added it.)
171
172       glibc 2.2 adds one further flag character.
173
174       I      For decimal integer conversion (i, d, u) the output uses the lo‐
175              cale's alternative output digits, if any.   For  example,  since
176              glibc  2.2.3  this  will give Arabic-Indic digits in the Persian
177              ("fa_IR") locale.
178
179   Field width
180       An optional decimal digit string (with nonzero first digit)  specifying
181       a  minimum  field  width.   If the converted value has fewer characters
182       than the field width, it will be padded with spaces  on  the  left  (or
183       right, if the left-adjustment flag has been given).  Instead of a deci‐
184       mal digit string one may write "*" or "*m$" (for some  decimal  integer
185       m) to specify that the field width is given in the next argument, or in
186       the m-th argument, respectively, which must be of type int.  A negative
187       field  width is taken as a '-' flag followed by a positive field width.
188       In no case does a nonexistent or small field width cause truncation  of
189       a  field;  if the result of a conversion is wider than the field width,
190       the field is expanded to contain the conversion result.
191
192   Precision
193       An optional precision, in the form of a period ('.')   followed  by  an
194       optional  decimal  digit string.  Instead of a decimal digit string one
195       may write "*" or "*m$" (for some decimal integer m) to specify that the
196       precision  is  given in the next argument, or in the m-th argument, re‐
197       spectively, which must be of type int.  If the precision  is  given  as
198       just  '.',  the precision is taken to be zero.  A negative precision is
199       taken as if the precision were omitted.  This gives the minimum  number
200       of digits to appear for d, i, o, u, x, and X conversions, the number of
201       digits to appear after the radix character for a, A, e,  E,  f,  and  F
202       conversions,  the maximum number of significant digits for g and G con‐
203       versions, or the maximum number of characters  to  be  printed  from  a
204       string for s and S conversions.
205
206   Length modifier
207       Here, "integer conversion" stands for d, i, o, u, x, or X conversion.
208
209       hh     A  following  integer conversion corresponds to a signed char or
210              unsigned char argument, or a following n conversion  corresponds
211              to a pointer to a signed char argument.
212
213       h      A  following  integer  conversion  corresponds to a short or un‐
214              signed short argument, or a following n  conversion  corresponds
215              to a pointer to a short argument.
216
217       l      (ell)  A  following  integer conversion corresponds to a long or
218              unsigned long argument, or a following n conversion  corresponds
219              to  a  pointer  to  a long argument, or a following c conversion
220              corresponds to a wint_t argument, or a  following  s  conversion
221              corresponds to a pointer to wchar_t argument.
222
223       ll     (ell-ell).  A following integer conversion corresponds to a long
224              long or unsigned long long argument, or a following n conversion
225              corresponds to a pointer to a long long argument.
226
227       q      A synonym for ll.  This is a nonstandard extension, derived from
228              BSD; avoid its use in new code.
229
230       L      A following a, A, e, E, f, F, g, or G conversion corresponds  to
231              a long double argument.  (C99 allows %LF, but SUSv2 does not.)
232
233       j      A  following  integer  conversion  corresponds to an intmax_t or
234              uintmax_t argument, or a following n conversion corresponds to a
235              pointer to an intmax_t argument.
236
237       z      A  following  integer  conversion  corresponds  to  a  size_t or
238              ssize_t argument, or a following n conversion corresponds  to  a
239              pointer to a size_t argument.
240
241       Z      A  nonstandard  synonym for z that predates the appearance of z.
242              Do not use in new code.
243
244       t      A following integer conversion corresponds to a ptrdiff_t  argu‐
245              ment,  or a following n conversion corresponds to a pointer to a
246              ptrdiff_t argument.
247
248       SUSv3 specifies all of the above, except for those modifiers explicitly
249       noted as being nonstandard extensions.  SUSv2 specified only the length
250       modifiers h (in hd, hi, ho, hx, hX, hn) and l (in ld, li, lo,  lx,  lX,
251       ln, lc, ls) and L (in Le, LE, Lf, Lg, LG).
252
253       As  a nonstandard extension, the GNU implementations treats ll and L as
254       synonyms, so that one can, for example, write llg (as a synonym for the
255       standards-compliant  Lg) and Ld (as a synonym for the standards compli‐
256       ant lld).  Such usage is nonportable.
257
258   Conversion specifiers
259       A character that specifies the type of conversion to be  applied.   The
260       conversion specifiers and their meanings are:
261
262       d, i   The  int  argument is converted to signed decimal notation.  The
263              precision, if any, gives the minimum number of digits that  must
264              appear;  if  the  converted  value  requires fewer digits, it is
265              padded on the left with zeros.   The  default  precision  is  1.
266              When  0  is  printed with an explicit precision 0, the output is
267              empty.
268
269       o, u, x, X
270              The unsigned int argument is converted to  unsigned  octal  (o),
271              unsigned  decimal  (u),  or unsigned hexadecimal (x and X) nota‐
272              tion.  The letters abcdef are used for x conversions;  the  let‐
273              ters  ABCDEF are used for X conversions.  The precision, if any,
274              gives the minimum number of digits that must appear; if the con‐
275              verted  value  requires  fewer  digits, it is padded on the left
276              with zeros.  The default precision is 1.  When 0 is printed with
277              an explicit precision 0, the output is empty.
278
279       e, E   The  double  argument  is  rounded  and  converted  in the style
280              [-]d.ddde±dd where there is one digit (which is nonzero  if  the
281              argument  is nonzero) before the decimal-point character and the
282              number of digits after it is equal to the precision; if the pre‐
283              cision  is  missing, it is taken as 6; if the precision is zero,
284              no decimal-point character appears.  An E  conversion  uses  the
285              letter  E  (rather than e) to introduce the exponent.  The expo‐
286              nent always contains at least two digits; if the value is  zero,
287              the exponent is 00.
288
289       f, F   The double argument is rounded and converted to decimal notation
290              in the style [-]ddd.ddd, where the number of  digits  after  the
291              decimal-point character is equal to the precision specification.
292              If the precision is missing, it is taken as 6; if the  precision
293              is  explicitly  zero,  no decimal-point character appears.  If a
294              decimal point appears, at least one digit appears before it.
295
296              (SUSv2 does not know about F and says that character string rep‐
297              resentations  for infinity and NaN may be made available.  SUSv3
298              adds a specification for F.  The C99 standard specifies "[-]inf"
299              or  "[-]infinity" for infinity, and a string starting with "nan"
300              for NaN, in the case of f conversion, and "[-]INF" or "[-]INFIN‐
301              ITY" or "NAN" in the case of F conversion.)
302
303       g, G   The  double argument is converted in style f or e (or F or E for
304              G conversions).  The precision specifies the number of  signifi‐
305              cant  digits.   If the precision is missing, 6 digits are given;
306              if the precision is zero, it is treated as 1.  Style e  is  used
307              if  the  exponent from its conversion is less than -4 or greater
308              than or equal to the precision.  Trailing zeros are removed from
309              the  fractional part of the result; a decimal point appears only
310              if it is followed by at least one digit.
311
312       a, A   (C99; not in SUSv2, but added in SUSv3) For  a  conversion,  the
313              double  argument is converted to hexadecimal notation (using the
314              letters abcdef) in the style [-]0xh.hhhhp±d;  for  A  conversion
315              the  prefix 0X, the letters ABCDEF, and the exponent separator P
316              is used.  There is one  hexadecimal  digit  before  the  decimal
317              point,  and the number of digits after it is equal to the preci‐
318              sion.  The default precision suffices for an  exact  representa‐
319              tion  of  the  value if an exact representation in base 2 exists
320              and otherwise is sufficiently large  to  distinguish  values  of
321              type  double.  The digit before the decimal point is unspecified
322              for nonnormalized numbers, and nonzero but otherwise unspecified
323              for  normalized  numbers.  The exponent always contains at least
324              one digit; if the value is zero, the exponent is 0.
325
326       c      If no l modifier is present, the int argument is converted to an
327              unsigned  char, and the resulting character is written.  If an l
328              modifier is present, the wint_t  (wide  character)  argument  is
329              converted  to  a  multibyte sequence by a call to the wcrtomb(3)
330              function, with a conversion state starting in the initial state,
331              and the resulting multibyte string is written.
332
333       s      If  no  l  modifier is present: the const char * argument is ex‐
334              pected to be a pointer to an array of character type (pointer to
335              a string).  Characters from the array are written up to (but not
336              including) a terminating null byte ('\0');  if  a  precision  is
337              specified,  no more than the number specified are written.  If a
338              precision is given, no null byte need be present; if the  preci‐
339              sion is not specified, or is greater than the size of the array,
340              the array must contain a terminating null byte.
341
342              If an l modifier is present: the const wchar_t * argument is ex‐
343              pected  to  be  a  pointer to an array of wide characters.  Wide
344              characters from the array are converted to multibyte  characters
345              (each  by  a  call to the wcrtomb(3) function, with a conversion
346              state starting in the initial state before the first wide  char‐
347              acter),  up  to and including a terminating null wide character.
348              The resulting multibyte characters are written up  to  (but  not
349              including)  the terminating null byte.  If a precision is speci‐
350              fied, no more bytes than the number specified are  written,  but
351              no partial multibyte characters are written.  Note that the pre‐
352              cision determines the number of bytes written, not the number of
353              wide  characters  or screen positions.  The array must contain a
354              terminating null wide character, unless a precision is given and
355              it  is  so small that the number of bytes written exceeds it be‐
356              fore the end of the array is reached.
357
358       C      (Not in C99 or C11, but in SUSv2, SUSv3,  and  SUSv4.)   Synonym
359              for lc.  Don't use.
360
361       S      (Not  in  C99  or C11, but in SUSv2, SUSv3, and SUSv4.)  Synonym
362              for ls.  Don't use.
363
364       p      The void * pointer argument is printed in hexadecimal (as if  by
365              %#x or %#lx).
366
367       n      The number of characters written so far is stored into the inte‐
368              ger pointed to by the  corresponding  argument.   That  argument
369              shall  be  an  int *, or variant whose size matches the (option‐
370              ally) supplied integer length modifier.   No  argument  is  con‐
371              verted.   (This  specifier  is not supported by the bionic C li‐
372              brary.)  The behavior is undefined if the conversion  specifica‐
373              tion includes any flags, a field width, or a precision.
374
375       m      (Glibc  extension;  supported by uClibc and musl.)  Print output
376              of strerror(errno).  No argument is required.
377
378       %      A '%' is written.  No argument is converted.  The complete  con‐
379              version specification is '%%'.
380

RETURN VALUE

382       Upon successful return, these functions return the number of characters
383       printed (excluding the null byte used to end output to strings).
384
385       The functions snprintf() and vsnprintf() do not write  more  than  size
386       bytes  (including the terminating null byte ('\0')).  If the output was
387       truncated due to this limit, then the return value  is  the  number  of
388       characters  (excluding the terminating null byte) which would have been
389       written to the final string if enough space had been available.   Thus,
390       a  return  value  of  size or more means that the output was truncated.
391       (See also below under NOTES.)
392
393       If an output error is encountered, a negative value is returned.
394

ATTRIBUTES

396       For an  explanation  of  the  terms  used  in  this  section,  see  at‐
397       tributes(7).
398
399       ┌─────────────────────────────────────┬───────────────┬────────────────┐
400Interface                            Attribute     Value          
401       ├─────────────────────────────────────┼───────────────┼────────────────┤
402printf(), fprintf(), sprintf(),      │ Thread safety │ MT-Safe locale │
403snprintf(), vprintf(), vfprintf(),   │               │                │
404vsprintf(), vsnprintf()              │               │                │
405       └─────────────────────────────────────┴───────────────┴────────────────┘
406

CONFORMING TO

408       fprintf(),  printf(),  sprintf(),  vprintf(),  vfprintf(),  vsprintf():
409       POSIX.1-2001, POSIX.1-2008, C89, C99.
410
411       snprintf(), vsnprintf(): POSIX.1-2001, POSIX.1-2008, C99.
412
413       The dprintf() and vdprintf() functions were originally  GNU  extensions
414       that were later standardized in POSIX.1-2008.
415
416       Concerning  the  return  value  of snprintf(), SUSv2 and C99 contradict
417       each other: when snprintf() is called with size=0 then SUSv2 stipulates
418       an  unspecified  return  value  less than 1, while C99 allows str to be
419       NULL in this case, and gives the return value (as always) as the number
420       of  characters  that  would have been written in case the output string
421       has been large enough.  POSIX.1-2001 and later align  their  specifica‐
422       tion of snprintf() with C99.
423
424       glibc  2.1 adds length modifiers hh, j, t, and z and conversion charac‐
425       ters a and A.
426
427       glibc 2.2 adds the conversion character F with C99 semantics,  and  the
428       flag character I.
429

NOTES

431       Some programs imprudently rely on code such as the following
432
433           sprintf(buf, "%s some further text", buf);
434
435       to append text to buf.  However, the standards explicitly note that the
436       results are undefined if source and destination  buffers  overlap  when
437       calling  sprintf(), snprintf(), vsprintf(), and vsnprintf().  Depending
438       on the version of gcc(1) used, and the compiler options employed, calls
439       such as the above will not produce the expected results.
440
441       The  glibc  implementation  of the functions snprintf() and vsnprintf()
442       conforms to the C99 standard, that  is,  behaves  as  described  above,
443       since  glibc version 2.1.  Until glibc 2.0.6, they would return -1 when
444       the output was truncated.
445

BUGS

447       Because sprintf() and vsprintf() assume  an  arbitrarily  long  string,
448       callers must be careful not to overflow the actual space; this is often
449       impossible to assure.  Note that the length of the strings produced  is
450       locale-dependent  and  difficult  to  predict.   Use snprintf() and vs‐
451       nprintf() instead (or asprintf(3) and vasprintf(3)).
452
453       Code such as printf(foo); often indicates a bug, since foo may  contain
454       a  % character.  If foo comes from untrusted user input, it may contain
455       %n, causing the printf() call to write to memory and creating a securi‐
456       ty hole.
457

EXAMPLES

459       To print Pi to five decimal places:
460
461           #include <math.h>
462           #include <stdio.h>
463           fprintf(stdout, "pi = %.5f\n", 4 * atan(1.0));
464
465       To  print  a  date  and time in the form "Sunday, July 3, 10:02", where
466       weekday and month are pointers to strings:
467
468           #include <stdio.h>
469           fprintf(stdout, "%s, %s %d, %.2d:%.2d\n",
470                   weekday, month, day, hour, min);
471
472       Many countries use the day-month-year order.  Hence, an  international‐
473       ized  version must be able to print the arguments in an order specified
474       by the format:
475
476           #include <stdio.h>
477           fprintf(stdout, format,
478                   weekday, month, day, hour, min);
479
480       where format depends on locale, and may permute  the  arguments.   With
481       the value:
482
483           "%1$s, %3$d. %2$s, %4$d:%5$.2d\n"
484
485       one might obtain "Sonntag, 3. Juli, 10:02".
486
487       To allocate a sufficiently large string and print into it (code correct
488       for both glibc 2.0 and glibc 2.1):
489
490       #include <stdio.h>
491       #include <stdlib.h>
492       #include <stdarg.h>
493
494       char *
495       make_message(const char *fmt, ...)
496       {
497           int n = 0;
498           size_t size = 0;
499           char *p = NULL;
500           va_list ap;
501
502           /* Determine required size. */
503
504           va_start(ap, fmt);
505           n = vsnprintf(p, size, fmt, ap);
506           va_end(ap);
507
508           if (n < 0)
509               return NULL;
510
511           size = (size_t) n + 1;      /* One extra byte for '\0' */
512           p = malloc(size);
513           if (p == NULL)
514               return NULL;
515
516           va_start(ap, fmt);
517           n = vsnprintf(p, size, fmt, ap);
518           va_end(ap);
519
520           if (n < 0) {
521               free(p);
522               return NULL;
523           }
524
525           return p;
526       }
527
528       If truncation occurs in glibc versions prior to 2.0.6, this is  treated
529       as an error instead of being handled gracefully.
530

SEE ALSO

532       printf(1),  asprintf(3),  puts(3), scanf(3), setlocale(3), strfromd(3),
533       wcrtomb(3), wprintf(3), locale(5)
534

COLOPHON

536       This page is part of release 5.13 of the Linux  man-pages  project.   A
537       description  of  the project, information about reporting bugs, and the
538       latest    version    of    this    page,    can     be     found     at
539       https://www.kernel.org/doc/man-pages/.
540
541
542
543GNU                               2021-03-22                         PRINTF(3)
Impressum