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

NAME

6       fprintf, printf, snprintf, sprintf - print formatted output
7

SYNOPSIS

9       #include <stdio.h>
10
11       int fprintf(FILE *restrict stream, const char *restrict format, ...);
12       int printf(const char *restrict format, ...);
13       int snprintf(char *restrict s, size_t n,
14              const char *restrict format, ...);
15       int sprintf(char *restrict s, const char *restrict format, ...);
16
17

DESCRIPTION

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

RETURN VALUE

412       Upon  successful completion, the fprintf() and printf() functions shall
413       return the number of bytes transmitted.
414
415       Upon successful completion, the sprintf()  function  shall  return  the
416       number of bytes written to s, excluding the terminating null byte.
417
418       Upon  successful  completion,  the snprintf() function shall return the
419       number of bytes that would be written to  s  had  n  been  sufficiently
420       large excluding the terminating null byte.
421
422       If an output error was encountered, these functions shall return a neg‐
423       ative value.
424
425       If the value of n is zero on a call to  snprintf(),  nothing  shall  be
426       written,  the  number  of bytes that would have been written had n been
427       sufficiently large excluding the terminating null  shall  be  returned,
428       and s may be a null pointer.
429

ERRORS

431       For  the  conditions  under  which  fprintf() and printf() fail and may
432       fail, refer to fputc() or fputwc() .
433
434       In addition, all forms of fprintf() may fail if:
435
436       EILSEQ A wide-character code that does not correspond to a valid  char‐
437              acter has been detected.
438
439       EINVAL There are insufficient arguments.
440
441
442       The printf() and fprintf() functions may fail if:
443
444       ENOMEM Insufficient storage space is available.
445
446
447       The snprintf() function shall fail if:
448
449       EOVERFLOW
450              The  value of n is greater than {INT_MAX} or the number of bytes
451              needed to hold the output  excluding  the  terminating  null  is
452              greater than {INT_MAX}.
453
454
455       The following sections are informative.
456

EXAMPLES

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

APPLICATION USAGE

747       If the application calling fprintf() has any objects of type wint_t  or
748       wchar_t,  it  must  also  include  the  <wchar.h>  header to have these
749       objects defined.
750

RATIONALE

752       None.
753

FUTURE DIRECTIONS

755       None.
756

SEE ALSO

758       fputc() , fscanf() , setlocale() , strfmon() ,  wcrtomb()  ,  the  Base
759       Definitions   volume   of   IEEE Std 1003.1-2001,  Chapter  7,  Locale,
760       <stdio.h>, <wchar.h>
761
763       Portions of this text are reprinted and reproduced in  electronic  form
764       from IEEE Std 1003.1, 2003 Edition, Standard for Information Technology
765       -- Portable Operating System Interface (POSIX),  The  Open  Group  Base
766       Specifications  Issue  6,  Copyright  (C) 2001-2003 by the Institute of
767       Electrical and Electronics Engineers, Inc and The Open  Group.  In  the
768       event of any discrepancy between this version and the original IEEE and
769       The Open Group Standard, the original IEEE and The Open Group  Standard
770       is  the  referee document. The original Standard can be obtained online
771       at http://www.opengroup.org/unix/online.html .
772
773
774
775IEEE/The Open Group                  2003                           FPRINTF(P)
Impressum