1FPRINTF(3P)                POSIX Programmer's Manual               FPRINTF(3P)
2
3
4

PROLOG

6       This  manual  page is part of the POSIX Programmer's Manual.  The Linux
7       implementation of this interface may differ (consult the  corresponding
8       Linux  manual page for details of Linux behavior), or the interface may
9       not be implemented on Linux.
10

NAME

12       dprintf, fprintf, printf, snprintf, sprintf — print formatted output
13

SYNOPSIS

15       #include <stdio.h>
16
17       int dprintf(int fildes, const char *restrict format, ...);
18       int fprintf(FILE *restrict stream, const char *restrict format, ...);
19       int printf(const char *restrict format, ...);
20       int snprintf(char *restrict s, size_t n,
21           const char *restrict format, ...);
22       int sprintf(char *restrict s, const char *restrict format, ...);
23

DESCRIPTION

25       Excluding dprintf(): The functionality described on this reference page
26       is  aligned  with the ISO C standard. Any conflict between the require‐
27       ments described here and the ISO C standard is unintentional. This vol‐
28       ume of POSIX.1‐2017 defers to the ISO C standard.
29
30       The  fprintf()  function shall place output on the named output stream.
31       The printf() function shall place output on the standard output  stream
32       stdout.  The sprintf() function shall place output followed by the null
33       byte, '\0', in consecutive bytes starting  at  *s;  it  is  the  user's
34       responsibility to ensure that enough space is available.
35
36       The  dprintf()  function shall be equivalent to the fprintf() function,
37       except that dprintf() shall write output to the  file  associated  with
38       the  file descriptor specified by the fildes argument rather than place
39       output on a stream.
40
41       The snprintf() function shall be  equivalent  to  sprintf(),  with  the
42       addition of the n argument which states the size of the buffer referred
43       to by s.  If n is zero, nothing shall be written and s may  be  a  null
44       pointer.  Otherwise,  output  bytes beyond the n‐1st shall be discarded
45       instead of being written to the array, and a null byte  is  written  at
46       the end of the bytes actually written into the array.
47
48       If  copying  takes  place between objects that overlap as a result of a
49       call to sprintf() or snprintf(), the results are undefined.
50
51       Each of these functions converts, formats,  and  prints  its  arguments
52       under  control of the format.  The format is a character string, begin‐
53       ning and ending in its initial shift state, if any. The format is  com‐
54       posed of zero or more directives: ordinary characters, which are simply
55       copied to the output stream, and  conversion  specifications,  each  of
56       which  shall  result  in  the  fetching of zero or more arguments.  The
57       results are undefined if there are insufficient arguments for the  for‐
58       mat.   If  the  format  is exhausted while arguments remain, the excess
59       arguments shall be evaluated but are otherwise ignored.
60
61       Conversions can be applied to the nth argument after the format in  the
62       argument  list,  rather than to the next unused argument. In this case,
63       the conversion specifier character % (see below)  is  replaced  by  the
64       sequence   "%n$",   where   n   is  a  decimal  integer  in  the  range
65       [1,{NL_ARGMAX}], giving the position of the argument  in  the  argument
66       list.  This  feature provides for the definition of format strings that
67       select arguments in an order appropriate to specific languages (see the
68       EXAMPLES section).
69
70       The  format  can contain either numbered argument conversion specifica‐
71       tions (that is, "%n$" and "*m$"),  or  unnumbered  argument  conversion
72       specifications  (that is, % and *), but not both. The only exception to
73       this is that %% can be mixed with the "%n$" form. The results of mixing
74       numbered  and unnumbered argument specifications in a format string are
75       undefined. When numbered argument specifications are  used,  specifying
76       the  Nth  argument  requires  that  all the leading arguments, from the
77       first to the (N-1)th, are specified in the format string.
78
79       In format strings containing the "%n$" form  of  conversion  specifica‐
80       tion,  numbered  arguments  in the argument list can be referenced from
81       the format string as many times as required.
82
83       In format strings containing the % form  of  conversion  specification,
84       each  conversion  specification  uses  the first unused argument in the
85       argument list.
86
87       All forms of the fprintf() functions allow for the insertion of a  lan‐
88       guage-dependent radix character in the output string. The radix charac‐
89       ter is defined in the current locale  (category  LC_NUMERIC).   In  the
90       POSIX  locale, or in a locale where the radix character is not defined,
91       the radix character shall default to a <period> ('.').
92
93       Each conversion specification is introduced by the '%' character or  by
94       the  character  sequence  "%n$",  after  which  the following appear in
95       sequence:
96
97        *  Zero or more flags (in any order), which modify the meaning of  the
98           conversion specification.
99
100        *  An  optional minimum field width.  If the converted value has fewer
101           bytes than the field width, it shall be padded with <space> charac‐
102           ters by default on the left; it shall be padded on the right if the
103           left-adjustment flag ('-'), described below, is given to the  field
104           width.  The  field  width  takes  the  form of an <asterisk> ('*'),
105           described below, or a decimal integer.
106
107        *  An optional precision that gives the minimum number  of  digits  to
108           appear for the d, i, o, u, x, and X conversion specifiers; the num‐
109           ber of digits to appear after the radix character for the a, A,  e,
110           E,  f,  and F conversion specifiers; the maximum number of signifi‐
111           cant digits for the g and G conversion specifiers; or  the  maximum
112           number  of bytes to be printed from a string in the s and S conver‐
113           sion specifiers. The precision takes the form of a  <period>  ('.')
114           followed  either  by  an  <asterisk>  ('*'), described below, or an
115           optional decimal digit string, where a null digit string is treated
116           as  zero.  If  a precision appears with any other conversion speci‐
117           fier, the behavior is undefined.
118
119        *  An optional length modifier that specifies the size  of  the  argu‐
120           ment.
121
122        *  A conversion specifier character that indicates the type of conver‐
123           sion to be applied.
124
125       A field width, or precision, or both, may be indicated by an <asterisk>
126       ('*').   In  this case an argument of type int supplies the field width
127       or precision. Applications shall ensure that arguments specifying field
128       width,  or precision, or both appear in that order before the argument,
129       if any, to be converted. A negative field width is taken as a '-'  flag
130       followed by a positive field width. A negative precision is taken as if
131       the precision were omitted.  In format  strings  containing  the  "%n$"
132       form  of  a conversion specification, a field width or precision may be
133       indicated by the sequence "*m$", where m is a decimal  integer  in  the
134       range  [1,{NL_ARGMAX}]  giving the position in the argument list (after
135       the format argument) of an integer argument containing the field  width
136       or precision, for example:
137
138
139           printf("%1$d:%2$.*3$d:%4$.*3$d\n", hour, min, precision, sec);
140
141       The flag characters and their meanings are:
142
143       '       (The  <apostrophe>.)   The  integer  portion of the result of a
144               decimal conversion (%i, %d, %u, %f, %F, %g,  or  %G)  shall  be
145               formatted  with  thousands' grouping characters. For other con‐
146               versions the behavior is undefined. The  non-monetary  grouping
147               character is used.
148
149       -       The result of the conversion shall be left-justified within the
150               field.  The conversion is right-justified if this flag  is  not
151               specified.
152
153       +       The  result  of  a  signed conversion shall always begin with a
154               sign ('+' or '-').  The conversion shall begin with a sign only
155               when  a  negative value is converted if this flag is not speci‐
156               fied.
157
158       <space> If the first character of a signed conversion is not a sign  or
159               if  a  signed  conversion  results  in no characters, a <space>
160               shall be prefixed to the result. This means that if the <space>
161               and '+' flags both appear, the <space> flag shall be ignored.
162
163       #       Specifies  that  the value is to be converted to an alternative
164               form. For o conversion, it shall increase the precision, if and
165               only if necessary, to force the first digit of the result to be
166               a zero (if the value and precision are both 0, a  single  0  is
167               printed).  For  x or X conversion specifiers, a non-zero result
168               shall have 0x (or 0X) prefixed to it. For a, A, e, E, f, F,  g,
169               and  G conversion specifiers, the result shall always contain a
170               radix character, even if no digits follow the radix  character.
171               Without  this  flag, a radix character appears in the result of
172               these conversions only if a digit follows it. For g and G  con‐
173               version  specifiers,  trailing  zeros shall not be removed from
174               the result as they normally are. For  other  conversion  speci‐
175               fiers, the behavior is undefined.
176
177       0       For  d,  i,  o,  u, x, X, a, A, e, E, f, F, g, and G conversion
178               specifiers, leading zeros (following any indication of sign  or
179               base) are used to pad to the field width rather than performing
180               space padding, except when converting an infinity  or  NaN.  If
181               the '0' and '-' flags both appear, the '0' flag is ignored. For
182               d, i, o, u, x, and X conversion specifiers, if a  precision  is
183               specified,  the  '0'  flag  shall  be  ignored.  If the '0' and
184               <apostrophe> flags both appear,  the  grouping  characters  are
185               inserted before zero padding. For other conversions, the behav‐
186               ior is undefined.
187
188       The length modifiers and their meanings are:
189
190       hh      Specifies that a following d, i, o, u, x, or X conversion spec‐
191               ifier  applies  to a signed char or unsigned char argument (the
192               argument will have been promoted according to the integer  pro‐
193               motions,  but  its  value  shall be converted to signed char or
194               unsigned char before printing); or that a following  n  conver‐
195               sion specifier applies to a pointer to a signed char argument.
196
197       h       Specifies that a following d, i, o, u, x, or X conversion spec‐
198               ifier applies to a short or unsigned short argument (the  argu‐
199               ment  will  have  been promoted according to the integer promo‐
200               tions, but its value shall be converted to  short  or  unsigned
201               short before printing); or that a following n conversion speci‐
202               fier applies to a pointer to a short argument.
203
204       l (ell) Specifies that a following d, i, o, u, x, or X conversion spec‐
205               ifier  applies to a long or unsigned long argument; that a fol‐
206               lowing n conversion specifier applies to a pointer  to  a  long
207               argument;  that a following c conversion specifier applies to a
208               wint_t  argument;  that  a  following  s  conversion  specifier
209               applies to a pointer to a wchar_t argument; or has no effect on
210               a following a, A, e, E, f, F, g, or G conversion specifier.
211
212       ll (ell-ell)
213               Specifies that a following d, i, o, u, x, or X conversion spec‐
214               ifier applies to a long long or unsigned long long argument; or
215               that a following n conversion specifier applies to a pointer to
216               a long long argument.
217
218       j       Specifies that a following d, i, o, u, x, or X conversion spec‐
219               ifier applies to an intmax_t or uintmax_t argument; or  that  a
220               following  n  conversion  specifier  applies to a pointer to an
221               intmax_t argument.
222
223       z       Specifies that a following d, i, o, u, x, or X conversion spec‐
224               ifier  applies  to a size_t or the corresponding signed integer
225               type argument; or  that  a  following  n  conversion  specifier
226               applies  to a pointer to a signed integer type corresponding to
227               a size_t argument.
228
229       t       Specifies that a following d, i, o, u, x, or X conversion spec‐
230               ifier applies to a ptrdiff_t or the corresponding unsigned type
231               argument; or that a following n conversion specifier applies to
232               a pointer to a ptrdiff_t argument.
233
234       L       Specifies that a following a, A, e, E, f, F, g, or G conversion
235               specifier applies to a long double argument.
236
237       If a length modifier appears with any conversion specifier  other  than
238       as specified above, the behavior is undefined.
239
240       The conversion specifiers and their meanings are:
241
242       d, i    The  int argument shall be converted to a signed decimal in the
243               style "[-]dddd". The precision specifies the minimum number  of
244               digits  to  appear;  if the value being converted can be repre‐
245               sented in fewer digits,  it  shall  be  expanded  with  leading
246               zeros.  The  default  precision  is 1. The result of converting
247               zero with an explicit precision of zero shall be no characters.
248
249       o       The unsigned argument shall be converted to unsigned octal for‐
250               mat  in  the  style "dddd". The precision specifies the minimum
251               number of digits to appear; if the value being converted can be
252               represented  in fewer digits, it shall be expanded with leading
253               zeros. The default precision is 1.  The  result  of  converting
254               zero with an explicit precision of zero shall be no characters.
255
256       u       The  unsigned  argument  shall be converted to unsigned decimal
257               format in the style "dddd". The precision specifies the minimum
258               number of digits to appear; if the value being converted can be
259               represented in fewer digits, it shall be expanded with  leading
260               zeros.  The  default  precision  is 1. The result of converting
261               zero with an explicit precision of zero shall be no characters.
262
263       x       The unsigned argument shall be converted to unsigned  hexadeci‐
264               mal  format in the style "dddd"; the letters "abcdef" are used.
265               The precision specifies the minimum number of digits to appear;
266               if  the  value being converted can be represented in fewer dig‐
267               its, it shall be expanded with leading zeros. The default  pre‐
268               cision  is  1.  The  result of converting zero with an explicit
269               precision of zero shall be no characters.
270
271       X       Equivalent to the x conversion specifier, except  that  letters
272               "ABCDEF" are used instead of "abcdef".
273
274       f, F    The  double  argument shall be converted to decimal notation in
275               the style "[-]ddd.ddd", where the number of  digits  after  the
276               radix character is equal to the precision specification. If the
277               precision is missing, it shall be taken as 6; if the  precision
278               is explicitly zero and no '#' flag is present, no radix charac‐
279               ter shall appear. If a radix character appears,  at  least  one
280               digit  appears  before it. The low-order digit shall be rounded
281               in an implementation-defined manner.
282
283               A double argument representing an infinity shall  be  converted
284               in  one of the styles "[-]inf" or "[-]infinity"; which style is
285               implementation-defined. A double argument  representing  a  NaN
286               shall  be  converted  in  one  of  the  styles  "[-]nan(n-char-
287               sequence)" or "[-]nan"; which style, and the meaning of any  n-
288               char-sequence,  is  implementation-defined.  The  F  conversion
289               specifier produces  "INF",  "INFINITY",  or  "NAN"  instead  of
290               "inf", "infinity", or "nan", respectively.
291
292       e, E    The   double   argument   shall   be  converted  in  the  style
293               "[-]d.ddddd", where there is one digit before the radix char‐
294               acter  (which  is non-zero if the argument is non-zero) and the
295               number of digits after it is equal to  the  precision;  if  the
296               precision  is missing, it shall be taken as 6; if the precision
297               is zero and no '#' flag is present, no  radix  character  shall
298               appear.  The low-order digit shall be rounded in an implementa‐
299               tion-defined manner. The E conversion specifier shall produce a
300               number  with  'E'  instead of 'e' introducing the exponent. The
301               exponent shall always contain at least two digits. If the value
302               is zero, the exponent shall be zero.
303
304               A double argument representing an infinity or NaN shall be con‐
305               verted in the style of an f or F conversion specifier.
306
307       g, G    The double argument representing a floating-point number  shall
308               be converted in the style f or e (or in the style F or E in the
309               case of a G conversion specifier), depending on the value  con‐
310               verted  and  the  precision.  Let P equal the precision if non-
311               zero, 6 if the precision is omitted, or 1 if the  precision  is
312               zero. Then, if a conversion with style E would have an exponent
313               of X:
314
315               --  If P>X≥-4, the conversion shall be with style f (or F)  and
316                   precision P-(X+1).
317
318               --  Otherwise,  the conversion shall be with style e (or E) and
319                   precision P-1.
320
321               Finally, unless the '#' flag is used, any trailing zeros  shall
322               be  removed  from  the fractional portion of the result and the
323               decimal-point character shall be removed if there is  no  frac‐
324               tional portion remaining.
325
326               A double argument representing an infinity or NaN shall be con‐
327               verted in the style of an f or F conversion specifier.
328
329       a, A    A double argument representing a floating-point number shall be
330               converted  in  the  style  "[-]0xh.hhhhd", where there is one
331               hexadecimal digit (which shall be non-zero if the argument is a
332               normalized  floating-point number and is otherwise unspecified)
333               before the decimal-point character and the number of  hexadeci‐
334               mal digits after it is equal to the precision; if the precision
335               is missing and FLT_RADIX is a power of 2,  then  the  precision
336               shall  be  sufficient for an exact representation of the value;
337               if the precision is missing and FLT_RADIX is not a power of  2,
338               then the precision shall be sufficient to distinguish values of
339               type double, except that trailing zeros may be omitted; if  the
340               precision  is  zero and the '#' flag is not specified, no deci‐
341               mal-point character shall appear. The letters "abcdef" shall be
342               used  for  a  conversion and the letters "ABCDEF" for A conver‐
343               sion. The A conversion specifier produces a number with 'X' and
344               'P'  instead of 'x' and 'p'.  The exponent shall always contain
345               at least one digit, and only as many more digits  as  necessary
346               to  represent  the decimal exponent of 2. If the value is zero,
347               the exponent shall be zero.
348
349               A double argument representing an infinity or NaN shall be con‐
350               verted in the style of an f or F conversion specifier.
351
352       c       The  int  argument  shall be converted to an unsigned char, and
353               the resulting byte shall be written.
354
355               If an l (ell) qualifier is present, the wint_t  argument  shall
356               be  converted  as  if by an ls conversion specification with no
357               precision and an argument that points to a two-element array of
358               type  wchar_t,  the  first element of which contains the wint_t
359               argument to the ls conversion specification and the second ele‐
360               ment contains a null wide character.
361
362       s       The  argument  shall  be  a pointer to an array of char.  Bytes
363               from the array shall be written up to (but not  including)  any
364               terminating  null  byte. If the precision is specified, no more
365               than that many bytes shall be written. If the precision is  not
366               specified  or is greater than the size of the array, the appli‐
367               cation shall ensure that the array contains a null byte.
368
369               If an l (ell) qualifier is present, the  argument  shall  be  a
370               pointer  to an array of type wchar_t.  Wide characters from the
371               array shall be converted to characters (each as if by a call to
372               the  wcrtomb() function, with the conversion state described by
373               an mbstate_t object initialized to zero before the  first  wide
374               character  is converted) up to and including a terminating null
375               wide character. The resulting characters shall be written up to
376               (but  not  including) the terminating null character (byte). If
377               no precision is specified, the application  shall  ensure  that
378               the  array  contains  a null wide character.  If a precision is
379               specified, no more than that many characters (bytes)  shall  be
380               written  (including  shift  sequences,  if  any), and the array
381               shall contain a null wide character if, to equal the  character
382               sequence length given by the precision, the function would need
383               to access a wide character one past the end of the array. In no
384               case shall a partial character be written.
385
386       p       The  argument  shall  be  a  pointer to void.  The value of the
387               pointer is converted to a sequence of printable characters,  in
388               an implementation-defined manner.
389
390       n       The  argument  shall  be  a pointer to an integer into which is
391               written the number of bytes written to the  output  so  far  by
392               this  call  to  one  of the fprintf() functions. No argument is
393               converted.
394
395       C       Equivalent to lc.
396
397       S       Equivalent to ls.
398
399       %       Print a '%' character; no argument is converted.  The  complete
400               conversion specification shall be %%.
401
402       If  a  conversion  specification does not match one of the above forms,
403       the behavior is undefined. If any argument is not the correct type  for
404       the corresponding conversion specification, the behavior is undefined.
405
406       In no case shall a nonexistent or small field width cause truncation of
407       a field; if the result of a conversion is wider than the  field  width,
408       the  field shall be expanded to contain the conversion result.  Charac‐
409       ters generated by fprintf() and printf() are printed as if fputc()  had
410       been called.
411
412       For  the  a  and A conversion specifiers, if FLT_RADIX is a power of 2,
413       the value shall be correctly rounded to a hexadecimal  floating  number
414       with the given precision.
415
416       For  a  and  A  conversions,  if  FLT_RADIX is not a power of 2 and the
417       result is not exactly representable in the given precision, the  result
418       should be one of the two adjacent numbers in hexadecimal floating style
419       with the given precision, with the extra  stipulation  that  the  error
420       should have a correct sign for the current rounding direction.
421
422       For  the  e,  E, f, F, g, and G conversion specifiers, if the number of
423       significant decimal digits is at  most  DECIMAL_DIG,  then  the  result
424       should  be correctly rounded. If the number of significant decimal dig‐
425       its is more than DECIMAL_DIG but the source  value  is  exactly  repre‐
426       sentable  with  DECIMAL_DIG  digits, then the result should be an exact
427       representation with trailing zeros.  Otherwise,  the  source  value  is
428       bounded  by two adjacent decimal strings L < U, both having DECIMAL_DIG
429       significant digits; the value of the resultant decimal string D  should
430       satisfy  L  <= D <= U, with the extra stipulation that the error should
431       have a correct sign for the current rounding direction.
432
433       The last data modification and last file status  change  timestamps  of
434       the file shall be marked for update:
435
436        1. Between the call to a successful execution of fprintf() or printf()
437           and the next  successful  completion  of  a  call  to  fflush()  or
438           fclose() on the same stream or a call to exit() or abort()
439
440        2. Upon successful completion of a call to dprintf()
441

RETURN VALUE

443       Upon  successful  completion,  the  dprintf(),  fprintf(), and printf()
444       functions shall return the number of bytes transmitted.
445
446       Upon successful completion, the sprintf()  function  shall  return  the
447       number of bytes written to s, excluding the terminating null byte.
448
449       Upon  successful  completion,  the snprintf() function shall return the
450       number of bytes that would be written to  s  had  n  been  sufficiently
451       large excluding the terminating null byte.
452
453       If an output error was encountered, these functions shall return a neg‐
454       ative value and set errno to indicate the error.
455
456       If the value of n is zero on a call to  snprintf(),  nothing  shall  be
457       written,  the  number  of bytes that would have been written had n been
458       sufficiently large excluding the terminating null  shall  be  returned,
459       and s may be a null pointer.
460

ERRORS

462       For  the conditions under which dprintf(), fprintf(), and printf() fail
463       and may fail, refer to fputc() or fputwc().
464
465       In addition, all forms of fprintf() shall fail if:
466
467       EILSEQ A wide-character code that does not correspond to a valid  char‐
468              acter has been detected.
469
470       EOVERFLOW
471              The value to be returned is greater than {INT_MAX}.
472
473       The dprintf() function may fail if:
474
475       EBADF  The fildes argument is not a valid file descriptor.
476
477       The dprintf(), fprintf(), and printf() functions may fail if:
478
479       ENOMEM Insufficient storage space is available.
480
481       The snprintf() function shall fail if:
482
483       EOVERFLOW
484              The value of n is greater than {INT_MAX}.
485
486       The following sections are informative.
487

EXAMPLES

489   Printing Language-Independent Date and Time
490       The following statement can be used to print date and time using a lan‐
491       guage-independent format:
492
493
494           printf(format, weekday, month, day, hour, min);
495
496       For American usage, format could be a pointer to the following string:
497
498
499           "%s, %s %d, %d:%.2d\n"
500
501       This example would produce the following message:
502
503
504           Sunday, July 3, 10:02
505
506       For German usage, format could be a pointer to the following string:
507
508
509           "%1$s, %3$d. %2$s, %4$d:%5$.2d\n"
510
511       This definition of format would produce the following message:
512
513
514           Sonntag, 3. Juli, 10:02
515
516   Printing File Information
517       The following example prints information about the  type,  permissions,
518       and number of links of a specific file in a directory.
519
520       The first two calls to printf() use data decoded from a previous stat()
521       call. The user-defined strperm() function shall return a string similar
522       to the one at the beginning of the output for the following command:
523
524
525           ls -l
526
527       The next call to printf() outputs the owner's name if it is found using
528       getpwuid(); the getpwuid() function shall  return  a  passwd  structure
529       from  which  the name of the user is extracted. If the user name is not
530       found, the program instead prints out the numeric value of the user ID.
531
532       The next call prints out the group name  if  it  is  found  using  get‐
533       grgid();  getgrgid() is very similar to getpwuid() except that it shall
534       return group information based on the group number.  Once again, if the
535       group  is  not found, the program prints the numeric value of the group
536       for the entry.
537
538       The final call to printf() prints the size of the file.
539
540
541           #include <stdio.h>
542           #include <sys/types.h>
543           #include <pwd.h>
544           #include <grp.h>
545
546           char *strperm (mode_t);
547           ...
548           struct stat statbuf;
549           struct passwd *pwd;
550           struct group *grp;
551           ...
552           printf("%10.10s", strperm (statbuf.st_mode));
553           printf("%4d", statbuf.st_nlink);
554
555           if ((pwd = getpwuid(statbuf.st_uid)) != NULL)
556               printf(" %-8.8s", pwd->pw_name);
557           else
558               printf(" %-8ld", (long) statbuf.st_uid);
559
560           if ((grp = getgrgid(statbuf.st_gid)) != NULL)
561               printf(" %-8.8s", grp->gr_name);
562           else
563               printf(" %-8ld", (long) statbuf.st_gid);
564
565           printf("%9jd", (intmax_t) statbuf.st_size);
566           ...
567
568   Printing a Localized Date String
569       The following example gets a localized date string.  The  nl_langinfo()
570       function  shall  return  the localized date string, which specifies the
571       order and layout of the date. The strftime() function takes this infor‐
572       mation and, using the tm structure for values, places the date and time
573       information into datestring.  The printf() function then  outputs  dat‐
574       estring and the name of the entry.
575
576
577           #include <stdio.h>
578           #include <time.h>
579           #include <langinfo.h>
580           ...
581           struct dirent *dp;
582           struct tm *tm;
583           char datestring[256];
584           ...
585           strftime(datestring, sizeof(datestring), nl_langinfo (D_T_FMT), tm);
586
587           printf(" %s %s\n", datestring, dp->d_name);
588           ...
589
590   Printing Error Information
591       The  following  example  uses  fprintf()  to write error information to
592       standard error.
593
594       In the first group of calls, the program tries  to  open  the  password
595       lock  file  named  LOCKFILE.   If  the  file already exists, this is an
596       error, as indicated by the O_EXCL flag on the open() function.  If  the
597       call fails, the program assumes that someone else is updating the pass‐
598       word file, and the program exits.
599
600       The next group of calls saves a new password file as the current  pass‐
601       word file by creating a link between LOCKFILE and the new password file
602       PASSWDFILE.
603
604
605           #include <sys/types.h>
606           #include <sys/stat.h>
607           #include <fcntl.h>
608           #include <stdio.h>
609           #include <stdlib.h>
610           #include <unistd.h>
611           #include <string.h>
612           #include <errno.h>
613
614           #define LOCKFILE "/etc/ptmp"
615           #define PASSWDFILE "/etc/passwd"
616           ...
617           int pfd;
618           ...
619           if ((pfd = open(LOCKFILE, O_WRONLY | O_CREAT | O_EXCL,
620               S_IRUSR | S_IWUSR | S_IRGRP | S_IROTH)) == -1)
621           {
622               fprintf(stderr, "Cannot open /etc/ptmp. Try again later.\n");
623               exit(1);
624           }
625           ...
626           if (link(LOCKFILE,PASSWDFILE) == -1) {
627               fprintf(stderr, "Link error: %s\n", strerror(errno));
628               exit(1);
629           }
630           ...
631
632   Printing Usage Information
633       The following example checks to make sure the program has the necessary
634       arguments,  and  uses  fprintf()  to  print  usage  information  if the
635       expected number of arguments is not present.
636
637
638           #include <stdio.h>
639           #include <stdlib.h>
640           ...
641           char *Options = "hdbtl";
642           ...
643           if (argc < 2) {
644               fprintf(stderr, "Usage: %s -%s <file\n", argv[0], Options); exit(1);
645           }
646           ...
647
648   Formatting a Decimal String
649       The following example prints a key and data pair on stdout.   Note  use
650       of  the <asterisk> ('*') in the format string; this ensures the correct
651       number of decimal places for the element based on the  number  of  ele‐
652       ments requested.
653
654
655           #include <stdio.h>
656           ...
657           long i;
658           char *keystr;
659           int elementlen, len;
660           ...
661           while (len < elementlen) {
662           ...
663               printf("%s Element%0*ld\n", keystr, elementlen, i);
664           ...
665           }
666
667   Creating a Pathname
668       The  following example creates a pathname using information from a pre‐
669       vious getpwnam() function that returned the password database entry  of
670       the user.
671
672
673           #include <stdint.h>
674           #include <stdio.h>
675           #include <stdlib.h>
676           #include <string.h>
677           #include <sys/types.h>
678           #include <unistd.h>
679           ...
680           char *pathname;
681           struct passwd *pw;
682           size_t len;
683           ...
684           // digits required for pid_t is number of bits times
685           // log2(10) = approx 10/33
686           len = strlen(pw->pw_dir) + 1 + 1+(sizeof(pid_t)*80+32)/33 +
687               sizeof ".out";
688           pathname = malloc(len);
689           if (pathname != NULL)
690           {
691               snprintf(pathname, len, "%s/%jd.out", pw->pw_dir,
692                   (intmax_t)getpid());
693               ...
694           }
695
696   Reporting an Event
697       The  following  example loops until an event has timed out. The pause()
698       function waits forever unless  it  receives  a  signal.  The  fprintf()
699       statement  should  never  occur  due  to  the possible return values of
700       pause().
701
702
703           #include <stdio.h>
704           #include <unistd.h>
705           #include <string.h>
706           #include <errno.h>
707           ...
708           while (!event_complete) {
709           ...
710               if (pause() != -1 || errno != EINTR)
711                   fprintf(stderr, "pause: unknown error: %s\n", strerror(errno));
712           }
713           ...
714
715   Printing Monetary Information
716       The following example uses strfmon() to convert a number and  store  it
717       as  a  formatted monetary string named convbuf.  If the first number is
718       printed, the program prints the format and the description;  otherwise,
719       it just prints the number.
720
721
722           #include <monetary.h>
723           #include <stdio.h>
724           ...
725           struct tblfmt {
726               char *format;
727               char *description;
728           };
729
730           struct tblfmt table[] = {
731               { "%n", "default formatting" },
732               { "%11n", "right align within an 11 character field" },
733               { "%#5n", "aligned columns for values up to 99999" },
734               { "%=*#5n", "specify a fill character" },
735               { "%=0#5n", "fill characters do not use grouping" },
736               { "%^#5n", "disable the grouping separator" },
737               { "%^#5.0n", "round off to whole units" },
738               { "%^#5.4n", "increase the precision" },
739               { "%(#5n", "use an alternative pos/neg style" },
740               { "%!(#5n", "disable the currency symbol" },
741           };
742           ...
743           float input[3];
744           int i, j;
745           char convbuf[100];
746           ...
747           strfmon(convbuf, sizeof(convbuf), table[i].format, input[j]);
748
749           if (j == 0) {
750               printf("%s%s%s\n", table[i].format,
751                   convbuf, table[i].description);
752           }
753           else {
754               printf("%s\n", convbuf);
755           }
756           ...
757
758   Printing Wide Characters
759       The  following example prints a series of wide characters. Suppose that
760       "L`@`" expands to three bytes:
761
762
763           wchar_t wz [3] = L"@@";       // Zero-terminated
764           wchar_t wn [3] = L"@@@";      // Unterminated
765
766           fprintf (stdout,"%ls", wz);   // Outputs 6 bytes
767           fprintf (stdout,"%ls", wn);   // Undefined because wn has no terminator
768           fprintf (stdout,"%4ls", wz);  // Outputs 3 bytes
769           fprintf (stdout,"%4ls", wn);  // Outputs 3 bytes; no terminator needed
770           fprintf (stdout,"%9ls", wz);  // Outputs 6 bytes
771           fprintf (stdout,"%9ls", wn);  // Outputs 9 bytes; no terminator needed
772           fprintf (stdout,"%10ls", wz); // Outputs 6 bytes
773           fprintf (stdout,"%10ls", wn); // Undefined because wn has no terminator
774
775       In the last line of the example,  after  processing  three  characters,
776       nine bytes have been output. The fourth character must then be examined
777       to determine whether it converts to one byte or more. If it converts to
778       more  than  one  byte, the output is only nine bytes. Since there is no
779       fourth character in the array, the behavior is undefined.
780

APPLICATION USAGE

782       If the application calling fprintf() has any objects of type wint_t  or
783       wchar_t,  it  must  also  include  the  <wchar.h>  header to have these
784       objects defined.
785

RATIONALE

787       If an implementation detects that there are insufficient arguments  for
788       the  format, it is recommended that the function should fail and report
789       an [EINVAL] error.
790

FUTURE DIRECTIONS

792       None.
793

SEE ALSO

795       Section 2.5, Standard  I/O  Streams,  fputc(),  fscanf(),  setlocale(),
796       strfmon(), wcrtomb()
797
798       The  Base  Definitions volume of POSIX.1‐2017, Chapter 7, Locale, <int‐
799       types.h>, <stdio.h>, <wchar.h>
800
802       Portions of this text are reprinted and reproduced in  electronic  form
803       from  IEEE Std 1003.1-2017, Standard for Information Technology -- Por‐
804       table Operating System Interface (POSIX), The Open Group Base  Specifi‐
805       cations  Issue  7, 2018 Edition, Copyright (C) 2018 by the Institute of
806       Electrical and Electronics Engineers, Inc and The Open Group.   In  the
807       event of any discrepancy between this version and the original IEEE and
808       The Open Group Standard, the original IEEE and The Open Group  Standard
809       is  the  referee document. The original Standard can be obtained online
810       at http://www.opengroup.org/unix/online.html .
811
812       Any typographical or formatting errors that appear  in  this  page  are
813       most likely to have been introduced during the conversion of the source
814       files to man page format. To report such errors,  see  https://www.ker
815       nel.org/doc/man-pages/reporting_bugs.html .
816
817
818
819IEEE/The Open Group                  2017                          FPRINTF(3P)
Impressum