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

NAME

6       printf,   fprintf,  sprintf,  snprintf,  vprintf,  vfprintf,  vsprintf,
7       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 sprintf(char *str, const char *format, ...);
15       int snprintf(char *str, size_t size, const char *format, ...);
16
17       #include <stdarg.h>
18
19       int vprintf(const char *format, va_list ap);
20       int vfprintf(FILE *stream, const char *format, va_list ap);
21       int vsprintf(char *str, const char *format, va_list ap);
22       int vsnprintf(char *str, size_t size, const char *format, va_list ap);
23
24   Feature Test Macro Requirements for glibc (see feature_test_macros(7)):
25
26       snprintf(), vsnprintf():
27           _BSD_SOURCE || _XOPEN_SOURCE >= 500 || _ISOC99_SOURCE ||
28           _POSIX_C_SOURCE >= 200112L;
29           or cc -std=c99
30

DESCRIPTION

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

CONFORMING TO

354       The  fprintf(),  printf(),  sprintf(),   vprintf(),   vfprintf(),   and
355       vsprintf()  functions  conform  to  C89  and  C99.   The snprintf() and
356       vsnprintf() functions conform to C99.
357
358       Concerning the return value of snprintf(),  SUSv2  and  C99  contradict
359       each other: when snprintf() is called with size=0 then SUSv2 stipulates
360       an unspecified return value less than 1, while C99  allows  str  to  be
361       NULL in this case, and gives the return value (as always) as the number
362       of characters that would have been written in case  the  output  string
363       has been large enough.
364
365       Linux  libc4 knows about the five C standard flags.  It knows about the
366       length modifiers h, l, L, and the conversions c, d, e, E, f, F,  g,  G,
367       i,  n, o, p, s, u, x, and X, where F is a synonym for f.  Additionally,
368       it accepts D, O, and U as synonyms for ld, lo, and lu.  (This  is  bad,
369       and  caused  serious  bugs later, when support for %D disappeared.)  No
370       locale-dependent radix character, no thousands' separator,  no  NaN  or
371       infinity, no "%m$" and "*m$".
372
373       Linux  libc5  knows  about  the  five  C standard flags and the ' flag,
374       locale, "%m$" and "*m$".  It knows about the length modifiers h, l,  L,
375       Z,  and  q,  but accepts L and q both for long double and for long long
376       int (this is a bug).  It no longer recognizes F, D, O, and U, but  adds
377       the conversion character m, which outputs strerror(errno).
378
379       glibc 2.0 adds conversion characters C and S.
380
381       glibc  2.1 adds length modifiers hh, j, t, and z and conversion charac‐
382       ters a and A.
383
384       glibc 2.2 adds the conversion character F with C99 semantics,  and  the
385       flag character I.
386

NOTES

388       Some programs imprudently rely on code such as the following
389
390           sprintf(buf, "%s some further text", buf);
391
392       to append text to buf.  However, the standards explicitly note that the
393       results are undefined if source and destination  buffers  overlap  when
394       calling  sprintf(), snprintf(), vsprintf(), and vsnprintf().  Depending
395       on the version of gcc(1) used, and the compiler options employed, calls
396       such as the above will not produce the expected results.
397
398       The  glibc  implementation  of the functions snprintf() and vsnprintf()
399       conforms to the C99 standard, that  is,  behaves  as  described  above,
400       since  glibc  version 2.1.  Until glibc 2.0.6 they would return -1 when
401       the output was truncated.
402

BUGS

404       Because sprintf() and vsprintf() assume  an  arbitrarily  long  string,
405       callers must be careful not to overflow the actual space; this is often
406       impossible to assure.  Note that the length of the strings produced  is
407       locale-dependent   and   difficult  to  predict.   Use  snprintf()  and
408       vsnprintf() instead (or asprintf(3) and vasprintf(3)).
409
410       Linux libc4.[45] does not have a snprintf(), but provides a libbsd that
411       contains  an  snprintf()  equivalent  to  sprintf(),  that is, one that
412       ignores the size argument.  Thus, the  use  of  snprintf()  with  early
413       libc4 leads to serious security problems.
414
415       Code  such as printf(foo); often indicates a bug, since foo may contain
416       a % character.  If foo comes from untrusted user input, it may  contain
417       %n,  causing  the printf() call to write to memory and creating a secu‐
418       rity hole.
419

EXAMPLE

421       To print Pi to five decimal places:
422
423           #include <math.h>
424           #include <stdio.h>
425           fprintf(stdout, "pi = %.5f\n", 4 * atan(1.0));
426
427       To print a date and time in the form "Sunday,  July  3,  10:02",  where
428       weekday and month are pointers to strings:
429
430           #include <stdio.h>
431           fprintf(stdout, "%s, %s %d, %.2d:%.2d\n",
432                   weekday, month, day, hour, min);
433
434       Many  countries use the day-month-year order.  Hence, an international‐
435       ized version must be able to print the arguments in an order  specified
436       by the format:
437
438           #include <stdio.h>
439           fprintf(stdout, format,
440                   weekday, month, day, hour, min);
441
442       where  format  depends  on locale, and may permute the arguments.  With
443       the value:
444
445           "%1$s, %3$d. %2$s, %4$d:%5$.2d\n"
446
447       one might obtain "Sonntag, 3. Juli, 10:02".
448
449       To allocate a sufficiently large string and print into it (code correct
450       for both glibc 2.0 and glibc 2.1):
451
452       If  truncation occurs in glibc versions prior to 2.0.6, this is treated
453       as an error instead of being handled gracefully.
454
455       #include <stdio.h>
456       #include <stdlib.h>
457       #include <stdarg.h>
458
459       char *
460       make_message(const char *fmt, ...)
461       {
462           int n;
463           int size = 100;     /* Guess we need no more than 100 bytes */
464           char *p, *np;
465           va_list ap;
466
467           if ((p = malloc(size)) == NULL)
468               return NULL;
469
470           while (1) {
471
472               /* Try to print in the allocated space */
473
474               va_start(ap, fmt);
475               n = vsnprintf(p, size, fmt, ap);
476               va_end(ap);
477
478               /* Check error code */
479
480               if (n < 0)
481                   return NULL;
482
483               /* If that worked, return the string */
484
485               if (n < size)
486                   return p;
487
488               /* Else try again with more space */
489
490               size = n + 1;       /* Precisely what is needed */
491
492
493               if ((np = realloc (p, size)) == NULL) {
494                   free(p);
495                   return NULL;
496               } else {
497                   p = np;
498               }
499           }
500       }
501

SEE ALSO

503       printf(1), asprintf(3), dprintf(3), scanf(3), setlocale(3), wcrtomb(3),
504       wprintf(3), locale(5)
505

COLOPHON

507       This  page  is  part of release 3.53 of the Linux man-pages project.  A
508       description of the project, and information about reporting  bugs,  can
509       be found at http://www.kernel.org/doc/man-pages/.
510
511
512
513GNU                               2013-03-05                         PRINTF(3)
Impressum