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

DESCRIPTION

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

EXAMPLE

330       To print pi to five decimal places:
331              #include <math.h>
332              #include <stdio.h>
333              fprintf(stdout, "pi = %.5f\n", 4 * atan(1.0));
334
335       To  print  a  date  and time in the form `Sunday, July 3, 10:02', where
336       weekday and month are pointers to strings:
337              #include <stdio.h>
338              fprintf(stdout, "%s, %s %d, %.2d:%.2d\n",
339                   weekday, month, day, hour, min);
340
341       Many countries use the day-month-year order.  Hence, an  international‐
342       ized  version must be able to print the arguments in an order specified
343       by the format:
344              #include <stdio.h>
345              fprintf(stdout, format,
346                   weekday, month, day, hour, min);
347       where format depends on locale, and may permute the arguments. With the
348       value
349              "%1$s, %3$d. %2$s, %4$d:%5$.2d\n"
350       one might obtain `Sonntag, 3. Juli, 10:02'.
351
352       To allocate a sufficiently large string and print into it (code correct
353       for both glibc 2.0 and glibc 2.1):
354              #include <stdio.h>
355              #include <stdlib.h>
356              #include <stdarg.h>
357
358              char *
359              make_message(const char *fmt, ...) {
360                 /* Guess we need no more than 100 bytes. */
361                 int n, size = 100;
362                 char *p, *np;
363                 va_list ap;
364
365                 if ((p = malloc (size)) == NULL)
366                    return NULL;
367
368                 while (1) {
369                    /* Try to print in the allocated space. */
370                    va_start(ap, fmt);
371                    n = vsnprintf (p, size, fmt, ap);
372                    va_end(ap);
373                    /* If that worked, return the string. */
374                    if (n > -1 && n < size)
375                       return p;
376                    /* Else try again with more space. */
377                    if (n > -1)    /* glibc 2.1 */
378                       size = n+1; /* precisely what is needed */
379                    else           /* glibc 2.0 */
380                       size *= 2;  /* twice the old size */
381                    if ((np = realloc (p, size)) == NULL) {
382                       free(p);
383                       return NULL;
384                    } else {
385                       p = np;
386                    }
387                 }
388              }
389
390

NOTES

392       The glibc implementation of the functions  snprintf()  and  vsnprintf()
393       conforms  to  the C99 standard, i.e., behaves as described above, since
394       glibc version 2.1. Until glibc 2.0.6 they would return -1 when the out‐
395       put was truncated.
396

CONFORMING TO

398       The   fprintf(),   printf(),   sprintf(),  vprintf(),  vfprintf(),  and
399       vsprintf() functions conform  to  C89  and  C99.   The  snprintf()  and
400       vsnprintf() functions conform to C99.
401
402       Concerning  the  return  value  of snprintf(), SUSv2 and C99 contradict
403       each other: when snprintf() is called with size=0 then SUSv2 stipulates
404       an  unspecified  return  value  less than 1, while C99 allows str to be
405       NULL in this case, and gives the return value (as always) as the number
406       of  characters  that  would have been written in case the output string
407       has been large enough.
408
409       Linux libc4 knows about the five C standard flags.  It knows about  the
410       length  modifiers  h,l,L, and the conversions cdeEfFgGinopsuxX, where F
411       is a synonym for f.  Additionally, it accepts  D,O,U  as  synonyms  for
412       ld,lo,lu.   (This  is  bad, and caused serious bugs later, when support
413       for %D disappeared.) No locale-dependent radix character, no thousands'
414       separator, no NaN or infinity, no %m$ and *m$.
415
416       Linux  libc5  knows  about  the  five  C standard flags and the ' flag,
417       locale, %m$ and *m$.  It knows about the  length  modifiers  h,l,L,Z,q,
418       but  accepts  L  and q both for long doubles and for long long integers
419       (this is a bug).  It no longer recognizes FDOU, but adds the conversion
420       character m, which outputs strerror(errno).
421
422       glibc 2.0 adds conversion characters C and S.
423
424       glibc 2.1 adds length modifiers hh,j,t,z and conversion characters a,A.
425
426       glibc  2.2  adds the conversion character F with C99 semantics, and the
427       flag character I.
428

HISTORY

430       Unix V7 defines the three routines printf(), fprintf(), sprintf(),  and
431       has  the  flag  -, the width or precision *, the length modifier l, and
432       the  conversions  doxfegcsu,  and  also   D,O,U,X   as   synonyms   for
433       ld,lo,lu,lx.   This  is  still  true  for 2.9.1BSD, but 2.10BSD has the
434       flags #, + and <space> and no longer  mentions  D,O,U,X.   2.11BSD  has
435       vprintf(),  vfprintf(),  vsprintf(),  and  warns  not  to  use D,O,U,X.
436       4.3BSD Reno has the flag 0, the length modifiers h and L, and the  con‐
437       versions  n,  p,  E,  G, X (with current meaning) and deprecates D,O,U.
438       4.4BSD introduces the functions snprintf()  and  vsnprintf(),  and  the
439       length   modifier   q.   FreeBSD  also  has  functions  asprintf()  and
440       vasprintf(), that allocate a buffer large  enough  for  sprintf().   In
441       glibc there are functions dprintf() and vdprintf() that print to a file
442       descriptor instead of a stream.
443

BUGS

445       Because sprintf() and vsprintf() assume  an  arbitrarily  long  string,
446       callers must be careful not to overflow the actual space; this is often
447       impossible to assure. Note that the length of the strings  produced  is
448       locale-dependent   and   difficult  to  predict.   Use  snprintf()  and
449       vsnprintf() instead (or asprintf() and vasprintf).
450
451       Linux libc4.[45] does not have a snprintf(), but provides a libbsd that
452       contains  an snprintf() equivalent to sprintf(), i.e., one that ignores
453       the size argument.  Thus, the use of snprintf() with early libc4  leads
454       to serious security problems.
455
456       Code  such as printf(foo); often indicates a bug, since foo may contain
457       a % character.  If foo comes from untrusted user input, it may  contain
458       %n,  causing  the printf() call to write to memory and creating a secu‐
459       rity hole.
460
461

SEE ALSO

463       printf(1), asprintf(3), dprintf(3), scanf(3), setlocale(3), wcrtomb(3),
464       wprintf(3), locale(5)
465
466
467
468Linux Manpage                     2000-10-16                         PRINTF(3)
Impressum