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

NAME

6       printf,   fprintf,   dprintf,  sprintf,  snprintf,  vprintf,  vfprintf,
7       vdprintf, 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
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 before  the  decimal-point
269              character and the number of digits after it is equal to the pre‐
270              cision; if the precision is missing, it is taken as  6;  if  the
271              precision  is  zero,  no  decimal-point character appears.  An E
272              conversion uses the letter E (rather than e)  to  introduce  the
273              exponent.   The exponent always contains at least two digits; if
274              the value is zero, the exponent is 00.
275
276       f, F   The double argument is rounded and converted to decimal notation
277              in  the  style  [-]ddd.ddd, where the number of digits after the
278              decimal-point character is equal to the precision specification.
279              If  the precision is missing, it is taken as 6; if the precision
280              is explicitly zero, no decimal-point character  appears.   If  a
281              decimal point appears, at least one digit appears before it.
282
283              (SUSv2 does not know about F and says that character string rep‐
284              resentations for infinity and NaN may be made available.   SUSv3
285              adds a specification for F.  The C99 standard specifies "[-]inf"
286              or "[-]infinity" for infinity, and a string starting with  "nan"
287              for NaN, in the case of f conversion, and "[-]INF" or "[-]INFIN‐
288              ITY" or "NAN" in the case of F conversion.)
289
290       g, G   The double argument is converted in style f or e (or F or E  for
291              G  conversions).  The precision specifies the number of signifi‐
292              cant digits.  If the precision is missing, 6 digits  are  given;
293              if  the  precision is zero, it is treated as 1.  Style e is used
294              if the exponent from its conversion is less than -4  or  greater
295              than or equal to the precision.  Trailing zeros are removed from
296              the fractional part of the result; a decimal point appears  only
297              if it is followed by at least one digit.
298
299       a, A   (C99;  not  in  SUSv2, but added in SUSv3) For a conversion, the
300              double argument is converted to hexadecimal notation (using  the
301              letters abcdef) in the style [-]0xh.hhhhp±; for A conversion the
302              prefix 0X, the letters ABCDEF, and the exponent separator  P  is
303              used.   There is one hexadecimal digit before the decimal point,
304              and the number of digits after it is  equal  to  the  precision.
305              The  default  precision  suffices for an exact representation of
306              the value if an exact representation in base 2 exists and other‐
307              wise is sufficiently large to distinguish values of type double.
308              The digit before the decimal point is unspecified for nonnormal‐
309              ized  numbers, and nonzero but otherwise unspecified for normal‐
310              ized numbers.
311
312       c      If no l modifier is present, the int argument is converted to an
313              unsigned  char, and the resulting character is written.  If an l
314              modifier is present, the wint_t  (wide  character)  argument  is
315              converted  to  a  multibyte sequence by a call to the wcrtomb(3)
316              function, with a conversion state starting in the initial state,
317              and the resulting multibyte string is written.
318
319       s      If  no  l  modifier  is  present:  the  const char * argument is
320              expected to be a pointer to an array of character type  (pointer
321              to  a string).  Characters from the array are written up to (but
322              not including) a terminating null byte ('\0'); if a precision is
323              specified,  no more than the number specified are written.  If a
324              precision is given, no null byte need be present; if the  preci‐
325              sion is not specified, or is greater than the size of the array,
326              the array must contain a terminating null byte.
327
328              If an l modifier is present: the  const  wchar_t *  argument  is
329              expected  to  be a pointer to an array of wide characters.  Wide
330              characters from the array are converted to multibyte  characters
331              (each  by  a  call to the wcrtomb(3) function, with a conversion
332              state starting in the initial state before the first wide  char‐
333              acter),  up  to and including a terminating null wide character.
334              The resulting multibyte characters are written up  to  (but  not
335              including)  the terminating null byte.  If a precision is speci‐
336              fied, no more bytes than the number specified are  written,  but
337              no partial multibyte characters are written.  Note that the pre‐
338              cision determines the number of bytes written, not the number of
339              wide  characters  or screen positions.  The array must contain a
340              terminating null wide character, unless a precision is given and
341              it  is  so  small  that  the  number of bytes written exceeds it
342              before the end of the array is reached.
343
344       C      (Not in C99 or C11, but in SUSv2, SUSv3,  and  SUSv4.)   Synonym
345              for lc.  Don't use.
346
347       S      (Not  in  C99  or C11, but in SUSv2, SUSv3, and SUSv4.)  Synonym
348              for ls.  Don't use.
349
350       p      The void * pointer argument is printed in hexadecimal (as if  by
351              %#x or %#lx).
352
353       n      The number of characters written so far is stored into the inte‐
354              ger pointed to by the  corresponding  argument.   That  argument
355              shall  be  an  int *, or variant whose size matches the (option‐
356              ally) supplied integer length modifier.   No  argument  is  con‐
357              verted.   (This  specifier  is  not  supported  by  the bionic C
358              library.)  The behavior is undefined if the conversion  specifi‐
359              cation includes any flags, a field width, or a precision.
360
361       m      (Glibc  extension;  supported by uClibc and musl.)  Print output
362              of strerror(errno).  No argument is required.
363
364       %      A '%' is written.  No argument is converted.  The complete  con‐
365              version specification is '%%'.
366

RETURN VALUE

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

ATTRIBUTES

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

CONFORMING TO

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

NOTES

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

BUGS

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

EXAMPLE

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

SEE ALSO

518       printf(1),  asprintf(3),  puts(3), scanf(3), setlocale(3), strfromd(3),
519       wcrtomb(3), wprintf(3), locale(5)
520

COLOPHON

522       This page is part of release 4.15 of the Linux  man-pages  project.   A
523       description  of  the project, information about reporting bugs, and the
524       latest    version    of    this    page,    can     be     found     at
525       https://www.kernel.org/doc/man-pages/.
526
527
528
529GNU                               2017-09-15                         PRINTF(3)
Impressum