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 *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

DESCRIPTION

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 (in‐
49       cluding the terminating null byte ('\0')) to str.
50
51       The  functions  vprintf(),  vfprintf(),  vdprintf(),  vsprintf(),   vs‐
52       nprintf()   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  un‐
73       changed  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 re‐
86       quired, by writing "%m$" instead of '%' and "*m$" instead of '*', where
87       the  decimal integer m denotes the position in the argument list of the
88       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 de‐
108       pends 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 lo‐
163              cale'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, re‐
185       spectively, 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 or un‐
202              signed short argument, or a following n  conversion  corresponds
203              to a pointer to a short argument.
204
205       l      (ell)  A  following  integer conversion corresponds to a long or
206              unsigned long argument, or a following n conversion  corresponds
207              to  a  pointer  to  a long argument, or a following c conversion
208              corresponds to a wint_t argument, or a  following  s  conversion
209              corresponds to a pointer to wchar_t argument.
210
211       ll     (ell-ell).  A following integer conversion corresponds to a long
212              long or unsigned long long argument, or a following n conversion
213              corresponds to a pointer to a long long 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±d;  for  A  conversion
303              the  prefix 0X, the letters ABCDEF, and the exponent separator P
304              is used.  There is one  hexadecimal  digit  before  the  decimal
305              point,  and the number of digits after it is equal to the preci‐
306              sion.  The default precision suffices for an  exact  representa‐
307              tion  of  the  value if an exact representation in base 2 exists
308              and otherwise is sufficiently large  to  distinguish  values  of
309              type  double.  The digit before the decimal point is unspecified
310              for nonnormalized numbers, and nonzero but otherwise unspecified
311              for  normalized  numbers.  The exponent always contains at least
312              one digit; if the value is zero, the exponent is 0.
313
314       c      If no l modifier is present, the int argument is converted to an
315              unsigned  char, and the resulting character is written.  If an l
316              modifier is present, the wint_t  (wide  character)  argument  is
317              converted  to  a  multibyte sequence by a call to the wcrtomb(3)
318              function, with a conversion state starting in the initial state,
319              and the resulting multibyte string is written.
320
321       s      If  no  l  modifier is present: the const char * argument is ex‐
322              pected to be a pointer to an array of character type (pointer to
323              a string).  Characters from the array are written up to (but not
324              including) a terminating null byte ('\0');  if  a  precision  is
325              specified,  no more than the number specified are written.  If a
326              precision is given, no null byte need be present; if the  preci‐
327              sion is not specified, or is greater than the size of the array,
328              the array must contain a terminating null byte.
329
330              If an l modifier is present: the const wchar_t * argument is ex‐
331              pected  to  be  a  pointer to an array of wide characters.  Wide
332              characters from the array are converted to multibyte  characters
333              (each  by  a  call to the wcrtomb(3) function, with a conversion
334              state starting in the initial state before the first wide  char‐
335              acter),  up  to and including a terminating null wide character.
336              The resulting multibyte characters are written up  to  (but  not
337              including)  the terminating null byte.  If a precision is speci‐
338              fied, no more bytes than the number specified are  written,  but
339              no partial multibyte characters are written.  Note that the pre‐
340              cision determines the number of bytes written, not the number of
341              wide  characters  or screen positions.  The array must contain a
342              terminating null wide character, unless a precision is given and
343              it  is  so small that the number of bytes written exceeds it be‐
344              fore the end of the array is reached.
345
346       C      (Not in C99 or C11, but in SUSv2, SUSv3,  and  SUSv4.)   Synonym
347              for lc.  Don't use.
348
349       S      (Not  in  C99  or C11, but in SUSv2, SUSv3, and SUSv4.)  Synonym
350              for ls.  Don't use.
351
352       p      The void * pointer argument is printed in hexadecimal (as if  by
353              %#x or %#lx).
354
355       n      The number of characters written so far is stored into the inte‐
356              ger pointed to by the  corresponding  argument.   That  argument
357              shall  be  an  int *, or variant whose size matches the (option‐
358              ally) supplied integer length modifier.   No  argument  is  con‐
359              verted.   (This  specifier  is not supported by the bionic C li‐
360              brary.)  The behavior is undefined if the conversion  specifica‐
361              tion includes any flags, a field width, or a precision.
362
363       m      (Glibc  extension;  supported by uClibc and musl.)  Print output
364              of strerror(errno).  No argument is required.
365
366       %      A '%' is written.  No argument is converted.  The complete  con‐
367              version specification is '%%'.
368

RETURN VALUE

370       Upon successful return, these functions return the number of characters
371       printed (excluding the null byte used to end output to strings).
372
373       The functions snprintf() and vsnprintf() do not write  more  than  size
374       bytes  (including the terminating null byte ('\0')).  If the output was
375       truncated due to this limit, then the return value  is  the  number  of
376       characters  (excluding the terminating null byte) which would have been
377       written to the final string if enough space had been available.   Thus,
378       a  return  value  of  size or more means that the output was truncated.
379       (See also below under NOTES.)
380
381       If an output error is encountered, a negative value is returned.
382

ATTRIBUTES

384       For an  explanation  of  the  terms  used  in  this  section,  see  at‐
385       tributes(7).
386
387       ┌────────────────────────┬───────────────┬────────────────┐
388Interface               Attribute     Value          
389       ├────────────────────────┼───────────────┼────────────────┤
390printf(), fprintf(),    │ Thread safety │ MT-Safe locale │
391sprintf(), snprintf(),  │               │                │
392vprintf(), vfprintf(),  │               │                │
393vsprintf(), vsnprintf() │               │                │
394       └────────────────────────┴───────────────┴────────────────┘
395

CONFORMING TO

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

NOTES

420       Some programs imprudently rely on code such as the following
421
422           sprintf(buf, "%s some further text", buf);
423
424       to append text to buf.  However, the standards explicitly note that the
425       results are undefined if source and destination  buffers  overlap  when
426       calling  sprintf(), snprintf(), vsprintf(), and vsnprintf().  Depending
427       on the version of gcc(1) used, and the compiler options employed, calls
428       such as the above will not produce the expected results.
429
430       The  glibc  implementation  of the functions snprintf() and vsnprintf()
431       conforms to the C99 standard, that  is,  behaves  as  described  above,
432       since  glibc version 2.1.  Until glibc 2.0.6, they would return -1 when
433       the output was truncated.
434

BUGS

436       Because sprintf() and vsprintf() assume  an  arbitrarily  long  string,
437       callers must be careful not to overflow the actual space; this is often
438       impossible to assure.  Note that the length of the strings produced  is
439       locale-dependent  and  difficult  to  predict.   Use snprintf() and vs‐
440       nprintf() instead (or asprintf(3) and vasprintf(3)).
441
442       Code such as printf(foo); often indicates a bug, since foo may  contain
443       a  % character.  If foo comes from untrusted user input, it may contain
444       %n, causing the printf() call to write to memory and creating  a  secu‐
445       rity hole.
446

EXAMPLES

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

SEE ALSO

523       printf(1),  asprintf(3),  puts(3), scanf(3), setlocale(3), strfromd(3),
524       wcrtomb(3), wprintf(3), locale(5)
525

COLOPHON

527       This page is part of release 5.10 of the Linux  man-pages  project.   A
528       description  of  the project, information about reporting bugs, and the
529       latest    version    of    this    page,    can     be     found     at
530       https://www.kernel.org/doc/man-pages/.
531
532
533
534GNU                               2020-11-01                         PRINTF(3)
Impressum