1FPRINTF(3P) POSIX Programmer's Manual FPRINTF(3P)
2
3
4
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
11
13 dprintf, fprintf, printf, snprintf, sprintf — print formatted output
14
16 #include <stdio.h>
17
18 int dprintf(int fildes, const char *restrict format, ...);
19 int fprintf(FILE *restrict stream, const char *restrict format, ...);
20 int printf(const char *restrict format, ...);
21 int snprintf(char *restrict s, size_t n,
22 const char *restrict format, ...);
23 int sprintf(char *restrict s, const char *restrict format, ...);
24
26 Excluding dprintf(): The functionality described on this reference page
27 is aligned with the ISO C standard. Any conflict between the require‐
28 ments described here and the ISO C standard is unintentional. This vol‐
29 ume of POSIX.1‐2008 defers to the ISO C standard.
30
31 The fprintf() function shall place output on the named output stream.
32 The printf() function shall place output on the standard output stream
33 stdout. The sprintf() function shall place output followed by the null
34 byte, '\0', in consecutive bytes starting at *s; it is the user's
35 responsibility to ensure that enough space is available.
36
37 The dprintf() function shall be equivalent to the fprintf() function,
38 except that dprintf() shall write output to the file associated with
39 the file descriptor specified by the fildes argument rather than place
40 output on a stream.
41
42 The snprintf() function shall be equivalent to sprintf(), with the
43 addition of the n argument which states the size of the buffer referred
44 to by s. If n is zero, nothing shall be written and s may be a null
45 pointer. Otherwise, output bytes beyond the n‐1st shall be discarded
46 instead of being written to the array, and a null byte is written at
47 the end of the bytes actually written into the array.
48
49 If copying takes place between objects that overlap as a result of a
50 call to sprintf() or snprintf(), the results are undefined.
51
52 Each of these functions converts, formats, and prints its arguments
53 under control of the format. The format is a character string, begin‐
54 ning and ending in its initial shift state, if any. The format is com‐
55 posed of zero or more directives: ordinary characters, which are simply
56 copied to the output stream, and conversion specifications, each of
57 which shall result in the fetching of zero or more arguments. The
58 results are undefined if there are insufficient arguments for the for‐
59 mat. If the format is exhausted while arguments remain, the excess
60 arguments shall be evaluated but are otherwise ignored.
61
62 Conversions can be applied to the nth argument after the format in the
63 argument list, rather than to the next unused argument. In this case,
64 the conversion specifier character % (see below) is replaced by the
65 sequence "%n$", where n is a decimal integer in the range
66 [1,{NL_ARGMAX}], giving the position of the argument in the argument
67 list. This feature provides for the definition of format strings that
68 select arguments in an order appropriate to specific languages (see the
69 EXAMPLES section).
70
71 The format can contain either numbered argument conversion specifica‐
72 tions (that is, "%n$" and "*m$"), or unnumbered argument conversion
73 specifications (that is, % and *), but not both. The only exception to
74 this is that %% can be mixed with the "%n$" form. The results of mixing
75 numbered and unnumbered argument specifications in a format string are
76 undefined. When numbered argument specifications are used, specifying
77 the Nth argument requires that all the leading arguments, from the
78 first to the (N−1)th, are specified in the format string.
79
80 In format strings containing the "%n$" form of conversion specifica‐
81 tion, numbered arguments in the argument list can be referenced from
82 the format string as many times as required.
83
84 In format strings containing the % form of conversion specification,
85 each conversion specification uses the first unused argument in the
86 argument list.
87
88 All forms of the fprintf() functions allow for the insertion of a lan‐
89 guage-dependent radix character in the output string. The radix charac‐
90 ter is defined in the current locale (category LC_NUMERIC). In the
91 POSIX locale, or in a locale where the radix character is not defined,
92 the radix character shall default to a <period> ('.').
93
94 Each conversion specification is introduced by the '%' character or by
95 the character sequence "%n$", after which the following appear in
96 sequence:
97
98 * Zero or more flags (in any order), which modify the meaning of the
99 conversion specification.
100
101 * An optional minimum field width. If the converted value has fewer
102 bytes than the field width, it shall be padded with <space> charac‐
103 ters by default on the left; it shall be padded on the right if the
104 left-adjustment flag ('−'), described below, is given to the field
105 width. The field width takes the form of an <asterisk> ('*'),
106 described below, or a decimal integer.
107
108 * An optional precision that gives the minimum number of digits to
109 appear for the d, i, o, u, x, and X conversion specifiers; the num‐
110 ber of digits to appear after the radix character for the a, A, e,
111 E, f, and F conversion specifiers; the maximum number of signifi‐
112 cant digits for the g and G conversion specifiers; or the maximum
113 number of bytes to be printed from a string in the s and S conver‐
114 sion specifiers. The precision takes the form of a <period> ('.')
115 followed either by an <asterisk> ('*'), described below, or an
116 optional decimal digit string, where a null digit string is treated
117 as zero. If a precision appears with any other conversion speci‐
118 fier, the behavior is undefined.
119
120 * An optional length modifier that specifies the size of the argu‐
121 ment.
122
123 * A conversion specifier character that indicates the type of conver‐
124 sion to be applied.
125
126 A field width, or precision, or both, may be indicated by an <asterisk>
127 ('*'). In this case an argument of type int supplies the field width
128 or precision. Applications shall ensure that arguments specifying field
129 width, or precision, or both appear in that order before the argument,
130 if any, to be converted. A negative field width is taken as a '−' flag
131 followed by a positive field width. A negative precision is taken as if
132 the precision were omitted. In format strings containing the "%n$"
133 form of a conversion specification, a field width or precision may be
134 indicated by the sequence "*m$", where m is a decimal integer in the
135 range [1,{NL_ARGMAX}] giving the position in the argument list (after
136 the format argument) of an integer argument containing the field width
137 or precision, for example:
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 increases the precision (if neces‐
165 sary) to force the first digit of the result to be zero. For x
166 or X conversion specifiers, a non-zero result shall have 0x (or
167 0X) prefixed to it. For a, A, e, E, f, F, g, and G conversion
168 specifiers, the result shall always contain a radix character,
169 even if no digits follow the radix character. Without this
170 flag, a radix character appears in the result of these conver‐
171 sions only if a digit follows it. For g and G conversion speci‐
172 fiers, trailing zeros shall not be removed from the result as
173 they normally are. For other conversion specifiers, the behav‐
174 ior is undefined.
175
176 0 For d, i, o, u, x, X, a, A, e, E, f, F, g, and G conversion
177 specifiers, leading zeros (following any indication of sign or
178 base) are used to pad to the field width rather than performing
179 space padding, except when converting an infinity or NaN. If
180 the '0' and '−' flags both appear, the '0' flag is ignored. For
181 d, i, o, u, x, and X conversion specifiers, if a precision is
182 specified, the '0' flag shall be ignored. If the '0' and
183 <apostrophe> flags both appear, the grouping characters are
184 inserted before zero padding. For other conversions, the behav‐
185 ior is undefined.
186
187 The length modifiers and their meanings are:
188
189 hh Specifies that a following d, i, o, u, x, or X conversion spec‐
190 ifier applies to a signed char or unsigned char argument (the
191 argument will have been promoted according to the integer pro‐
192 motions, but its value shall be converted to signed char or
193 unsigned char before printing); or that a following n conver‐
194 sion specifier applies to a pointer to a signed char argument.
195
196 h Specifies that a following d, i, o, u, x, or X conversion spec‐
197 ifier applies to a short or unsigned short argument (the argu‐
198 ment will have been promoted according to the integer promo‐
199 tions, but its value shall be converted to short or unsigned
200 short before printing); or that a following n conversion speci‐
201 fier applies to a pointer to a short argument.
202
203 l (ell) Specifies that a following d, i, o, u, x, or X conversion spec‐
204 ifier applies to a long or unsigned long argument; that a fol‐
205 lowing n conversion specifier applies to a pointer to a long
206 argument; that a following c conversion specifier applies to a
207 wint_t argument; that a following s conversion specifier
208 applies to a pointer to a wchar_t argument; or has no effect on
209 a following a, A, e, E, f, F, g, or G conversion specifier.
210
211 ll (ell-ell)
212 Specifies that a following d, i, o, u, x, or X conversion spec‐
213 ifier applies to a long long or unsigned long long argument; or
214 that a following n conversion specifier applies to a pointer to
215 a long long argument.
216
217 j Specifies that a following d, i, o, u, x, or X conversion spec‐
218 ifier applies to an intmax_t or uintmax_t argument; or that a
219 following n conversion specifier applies to a pointer to an
220 intmax_t argument.
221
222 z Specifies that a following d, i, o, u, x, or X conversion spec‐
223 ifier applies to a size_t or the corresponding signed integer
224 type argument; or that a following n conversion specifier
225 applies to a pointer to a signed integer type corresponding to
226 a size_t argument.
227
228 t Specifies that a following d, i, o, u, x, or X conversion spec‐
229 ifier applies to a ptrdiff_t or the corresponding unsigned type
230 argument; or that a following n conversion specifier applies to
231 a pointer to a ptrdiff_t argument.
232
233 L Specifies that a following a, A, e, E, f, F, g, or G conversion
234 specifier applies to a long double argument.
235
236 If a length modifier appears with any conversion specifier other than
237 as specified above, the behavior is undefined.
238
239 The conversion specifiers and their meanings are:
240
241 d, i The int argument shall be converted to a signed decimal in the
242 style "[−]dddd". The precision specifies the minimum number of
243 digits to appear; if the value being converted can be repre‐
244 sented in fewer digits, it shall be expanded with leading
245 zeros. The default precision is 1. The result of converting
246 zero with an explicit precision of zero shall be no characters.
247
248 o The unsigned argument shall be converted to unsigned octal for‐
249 mat in the style "dddd". The precision specifies the minimum
250 number of digits to appear; if the value being converted can be
251 represented in fewer digits, it shall be expanded with leading
252 zeros. The default precision is 1. The result of converting
253 zero with an explicit precision of zero shall be no characters.
254
255 u The unsigned argument shall be converted to unsigned decimal
256 format in the style "dddd". The precision specifies the minimum
257 number of digits to appear; if the value being converted can be
258 represented in fewer digits, it shall be expanded with leading
259 zeros. The default precision is 1. The result of converting
260 zero with an explicit precision of zero shall be no characters.
261
262 x The unsigned argument shall be converted to unsigned hexadeci‐
263 mal format in the style "dddd"; the letters "abcdef" are used.
264 The precision specifies the minimum number of digits to appear;
265 if the value being converted can be represented in fewer dig‐
266 its, it shall be expanded with leading zeros. The default pre‐
267 cision is 1. The result of converting zero with an explicit
268 precision of zero shall be no characters.
269
270 X Equivalent to the x conversion specifier, except that letters
271 "ABCDEF" are used instead of "abcdef".
272
273 f, F The double argument shall be converted to decimal notation in
274 the style "[−]ddd.ddd", where the number of digits after the
275 radix character is equal to the precision specification. If the
276 precision is missing, it shall be taken as 6; if the precision
277 is explicitly zero and no '#' flag is present, no radix charac‐
278 ter shall appear. If a radix character appears, at least one
279 digit appears before it. The low-order digit shall be rounded
280 in an implementation-defined manner.
281
282 A double argument representing an infinity shall be converted
283 in one of the styles "[−]inf" or "[−]infinity"; which style is
284 implementation-defined. A double argument representing a NaN
285 shall be converted in one of the styles "[−]nan(n-char-
286 sequence)" or "[−]nan"; which style, and the meaning of any n-
287 char-sequence, is implementation-defined. The F conversion
288 specifier produces "INF", "INFINITY", or "NAN" instead of
289 "inf", "infinity", or "nan", respectively.
290
291 e, E The double argument shall be converted in the style
292 "[−]d.ddde±dd", where there is one digit before the radix char‐
293 acter (which is non-zero if the argument is non-zero) and the
294 number of digits after it is equal to the precision; if the
295 precision is missing, it shall be taken as 6; if the precision
296 is zero and no '#' flag is present, no radix character shall
297 appear. The low-order digit shall be rounded in an implementa‐
298 tion-defined manner. The E conversion specifier shall produce a
299 number with 'E' instead of 'e' introducing the exponent. The
300 exponent shall always contain at least two digits. If the value
301 is zero, the exponent shall be zero.
302
303 A double argument representing an infinity or NaN shall be con‐
304 verted in the style of an f or F conversion specifier.
305
306 g, G The double argument representing a floating-point number shall
307 be converted in the style f or e (or in the style F or E in the
308 case of a G conversion specifier), depending on the value con‐
309 verted and the precision. Let P equal the precision if non-
310 zero, 6 if the precision is omitted, or 1 if the precision is
311 zero. Then, if a conversion with style E would have an exponent
312 of X:
313
314 -- If P>X≥−4, the conversion shall be with style f (or F) and
315 precision P−(X+1).
316
317 -- Otherwise, the conversion shall be with style e (or E) and
318 precision P−1.
319
320 Finally, unless the '#' flag is used, any trailing zeros shall
321 be removed from the fractional portion of the result and the
322 decimal-point character shall be removed if there is no frac‐
323 tional portion remaining.
324
325 A double argument representing an infinity or NaN shall be con‐
326 verted in the style of an f or F conversion specifier.
327
328 a, A A double argument representing a floating-point number shall be
329 converted in the style "[−]0xh.hhhhp±d", where there is one
330 hexadecimal digit (which shall be non-zero if the argument is a
331 normalized floating-point number and is otherwise unspecified)
332 before the decimal-point character and the number of hexadeci‐
333 mal digits after it is equal to the precision; if the precision
334 is missing and FLT_RADIX is a power of 2, then the precision
335 shall be sufficient for an exact representation of the value;
336 if the precision is missing and FLT_RADIX is not a power of 2,
337 then the precision shall be sufficient to distinguish values of
338 type double, except that trailing zeros may be omitted; if the
339 precision is zero and the '#' flag is not specified, no deci‐
340 mal-point character shall appear. The letters "abcdef" shall be
341 used for a conversion and the letters "ABCDEF" for A conver‐
342 sion. The A conversion specifier produces a number with 'X' and
343 'P' instead of 'x' and 'p'. The exponent shall always contain
344 at least one digit, and only as many more digits as necessary
345 to represent the decimal exponent of 2. If the value is zero,
346 the exponent shall be zero.
347
348 A double argument representing an infinity or NaN shall be con‐
349 verted in the style of an f or F conversion specifier.
350
351 c The int argument shall be converted to an unsigned char, and
352 the resulting byte shall be written.
353
354 If an l (ell) qualifier is present, the wint_t argument shall
355 be converted as if by an ls conversion specification with no
356 precision and an argument that points to a two-element array of
357 type wchar_t, the first element of which contains the wint_t
358 argument to the ls conversion specification and the second ele‐
359 ment contains a null wide character.
360
361 s The argument shall be a pointer to an array of char. Bytes
362 from the array shall be written up to (but not including) any
363 terminating null byte. If the precision is specified, no more
364 than that many bytes shall be written. If the precision is not
365 specified or is greater than the size of the array, the appli‐
366 cation shall ensure that the array contains a null byte.
367
368 If an l (ell) qualifier is present, the argument shall be a
369 pointer to an array of type wchar_t. Wide characters from the
370 array shall be converted to characters (each as if by a call to
371 the wcrtomb() function, with the conversion state described by
372 an mbstate_t object initialized to zero before the first wide
373 character is converted) up to and including a terminating null
374 wide character. The resulting characters shall be written up to
375 (but not including) the terminating null character (byte). If
376 no precision is specified, the application shall ensure that
377 the array contains a null wide character. If a precision is
378 specified, no more than that many characters (bytes) shall be
379 written (including shift sequences, if any), and the array
380 shall contain a null wide character if, to equal the character
381 sequence length given by the precision, the function would need
382 to access a wide character one past the end of the array. In no
383 case shall a partial character be written.
384
385 p The argument shall be a pointer to void. The value of the
386 pointer is converted to a sequence of printable characters, in
387 an implementation-defined manner.
388
389 n The argument shall be a pointer to an integer into which is
390 written the number of bytes written to the output so far by
391 this call to one of the fprintf() functions. No argument is
392 converted.
393
394 C Equivalent to lc.
395
396 S Equivalent to ls.
397
398 % Print a '%' character; no argument is converted. The complete
399 conversion specification shall be %%.
400
401 If a conversion specification does not match one of the above forms,
402 the behavior is undefined. If any argument is not the correct type for
403 the corresponding conversion specification, the behavior is undefined.
404
405 In no case shall a nonexistent or small field width cause truncation of
406 a field; if the result of a conversion is wider than the field width,
407 the field shall be expanded to contain the conversion result. Charac‐
408 ters generated by fprintf() and printf() are printed as if fputc() had
409 been called.
410
411 For the a and A conversion specifiers, if FLT_RADIX is a power of 2,
412 the value shall be correctly rounded to a hexadecimal floating number
413 with the given precision.
414
415 For a and A conversions, if FLT_RADIX is not a power of 2 and the
416 result is not exactly representable in the given precision, the result
417 should be one of the two adjacent numbers in hexadecimal floating style
418 with the given precision, with the extra stipulation that the error
419 should have a correct sign for the current rounding direction.
420
421 For the e, E, f, F, g, and G conversion specifiers, if the number of
422 significant decimal digits is at most DECIMAL_DIG, then the result
423 should be correctly rounded. If the number of significant decimal dig‐
424 its is more than DECIMAL_DIG but the source value is exactly repre‐
425 sentable with DECIMAL_DIG digits, then the result should be an exact
426 representation with trailing zeros. Otherwise, the source value is
427 bounded by two adjacent decimal strings L < U, both having DECIMAL_DIG
428 significant digits; the value of the resultant decimal string D should
429 satisfy L <= D <= U, with the extra stipulation that the error should
430 have a correct sign for the current rounding direction.
431
432 The last data modification and last file status change timestamps of
433 the file shall be marked for update:
434
435 1. Between the call to a successful execution of fprintf() or printf()
436 and the next successful completion of a call to fflush() or
437 fclose() on the same stream or a call to exit() or abort()
438
439 2. Upon successful completion of a call to dprintf()
440
442 Upon successful completion, the dprintf(), fprintf(), and printf()
443 functions shall return the number of bytes transmitted.
444
445 Upon successful completion, the sprintf() function shall return the
446 number of bytes written to s, excluding the terminating null byte.
447
448 Upon successful completion, the snprintf() function shall return the
449 number of bytes that would be written to s had n been sufficiently
450 large excluding the terminating null byte.
451
452 If an output error was encountered, these functions shall return a neg‐
453 ative value and set errno to indicate the error.
454
455 If the value of n is zero on a call to snprintf(), nothing shall be
456 written, the number of bytes that would have been written had n been
457 sufficiently large excluding the terminating null shall be returned,
458 and s may be a null pointer.
459
461 For the conditions under which dprintf(), fprintf(), and printf() fail
462 and may fail, refer to fputc() or fputwc().
463
464 In addition, all forms of fprintf() shall fail if:
465
466 EILSEQ A wide-character code that does not correspond to a valid char‐
467 acter has been detected.
468
469 EOVERFLOW
470 The value to be returned is greater than {INT_MAX}.
471
472 In addition, all forms of fprintf() may fail if:
473
474 EINVAL There are insufficient arguments.
475
476 The dprintf() function may fail if:
477
478 EBADF The fildes argument is not a valid file descriptor.
479
480 The dprintf(), fprintf(), and printf() functions may fail if:
481
482 ENOMEM Insufficient storage space is available.
483
484 The snprintf() function shall fail if:
485
486 EOVERFLOW
487 The value of n is greater than {INT_MAX}.
488
489 The following sections are informative.
490
492 Printing Language-Independent Date and Time
493 The following statement can be used to print date and time using a lan‐
494 guage-independent format:
495
496 printf(format, weekday, month, day, hour, min);
497
498 For American usage, format could be a pointer to the following string:
499
500 "%s, %s %d, %d:%.2d\n"
501
502 This example would produce the following message:
503
504 Sunday, July 3, 10:02
505
506 For German usage, format could be a pointer to the following string:
507
508 "%1$s, %3$d. %2$s, %4$d:%5$.2d\n"
509
510 This definition of format would produce the following message:
511
512 Sonntag, 3. Juli, 10:02
513
514 Printing File Information
515 The following example prints information about the type, permissions,
516 and number of links of a specific file in a directory.
517
518 The first two calls to printf() use data decoded from a previous stat()
519 call. The user-defined strperm() function shall return a string similar
520 to the one at the beginning of the output for the following command:
521
522 ls −l
523
524 The next call to printf() outputs the owner's name if it is found using
525 getpwuid(); the getpwuid() function shall return a passwd structure
526 from which the name of the user is extracted. If the user name is not
527 found, the program instead prints out the numeric value of the user ID.
528
529 The next call prints out the group name if it is found using get‐
530 grgid(); getgrgid() is very similar to getpwuid() except that it shall
531 return group information based on the group number. Once again, if the
532 group is not found, the program prints the numeric value of the group
533 for the entry.
534
535 The final call to printf() prints the size of the file.
536
537 #include <stdio.h>
538 #include <sys/types.h>
539 #include <pwd.h>
540 #include <grp.h>
541
542 char *strperm (mode_t);
543 ...
544 struct stat statbuf;
545 struct passwd *pwd;
546 struct group *grp;
547 ...
548 printf("%10.10s", strperm (statbuf.st_mode));
549 printf("%4d", statbuf.st_nlink);
550
551 if ((pwd = getpwuid(statbuf.st_uid)) != NULL)
552 printf(" %−8.8s", pwd->pw_name);
553 else
554 printf(" %−8ld", (long) statbuf.st_uid);
555
556 if ((grp = getgrgid(statbuf.st_gid)) != NULL)
557 printf(" %−8.8s", grp->gr_name);
558 else
559 printf(" %−8ld", (long) statbuf.st_gid);
560
561 printf("%9jd", (intmax_t) statbuf.st_size);
562 ...
563
564 Printing a Localized Date String
565 The following example gets a localized date string. The nl_langinfo()
566 function shall return the localized date string, which specifies the
567 order and layout of the date. The strftime() function takes this infor‐
568 mation and, using the tm structure for values, places the date and time
569 information into datestring. The printf() function then outputs dat‐
570 estring and the name of the entry.
571
572 #include <stdio.h>
573 #include <time.h>
574 #include <langinfo.h>
575 ...
576 struct dirent *dp;
577 struct tm *tm;
578 char datestring[256];
579 ...
580 strftime(datestring, sizeof(datestring), nl_langinfo (D_T_FMT), tm);
581
582 printf(" %s %s\n", datestring, dp->d_name);
583 ...
584
585 Printing Error Information
586 The following example uses fprintf() to write error information to
587 standard error.
588
589 In the first group of calls, the program tries to open the password
590 lock file named LOCKFILE. If the file already exists, this is an
591 error, as indicated by the O_EXCL flag on the open() function. If the
592 call fails, the program assumes that someone else is updating the pass‐
593 word file, and the program exits.
594
595 The next group of calls saves a new password file as the current pass‐
596 word file by creating a link between LOCKFILE and the new password file
597 PASSWDFILE.
598
599 #include <sys/types.h>
600 #include <sys/stat.h>
601 #include <fcntl.h>
602 #include <stdio.h>
603 #include <stdlib.h>
604 #include <unistd.h>
605 #include <string.h>
606 #include <errno.h>
607
608 #define LOCKFILE "/etc/ptmp"
609 #define PASSWDFILE "/etc/passwd"
610 ...
611 int pfd;
612 ...
613 if ((pfd = open(LOCKFILE, O_WRONLY | O_CREAT | O_EXCL,
614 S_IRUSR | S_IWUSR | S_IRGRP | S_IROTH)) == −1)
615 {
616 fprintf(stderr, "Cannot open /etc/ptmp. Try again later.\n");
617 exit(1);
618 }
619 ...
620 if (link(LOCKFILE,PASSWDFILE) == -1) {
621 fprintf(stderr, "Link error: %s\n", strerror(errno));
622 exit(1);
623 }
624 ...
625
626 Printing Usage Information
627 The following example checks to make sure the program has the necessary
628 arguments, and uses fprintf() to print usage information if the
629 expected number of arguments is not present.
630
631 #include <stdio.h>
632 #include <stdlib.h>
633 ...
634 char *Options = "hdbtl";
635 ...
636 if (argc < 2) {
637 fprintf(stderr, "Usage: %s -%s <file\n", argv[0], Options); exit(1);
638 }
639 ...
640
641 Formatting a Decimal String
642 The following example prints a key and data pair on stdout. Note use
643 of the <asterisk> ('*') in the format string; this ensures the correct
644 number of decimal places for the element based on the number of ele‐
645 ments requested.
646
647 #include <stdio.h>
648 ...
649 long i;
650 char *keystr;
651 int elementlen, len;
652 ...
653 while (len < elementlen) {
654 ...
655 printf("%s Element%0*ld\n", keystr, elementlen, i);
656 ...
657 }
658
659 Creating a Pathname
660 The following example creates a pathname using information from a pre‐
661 vious getpwnam() function that returned the password database entry of
662 the user.
663
664 #include <stdint.h>
665 #include <stdio.h>
666 #include <stdlib.h>
667 #include <string.h>
668 #include <sys/types.h>
669 #include <unistd.h>
670 ...
671 char *pathname;
672 struct passwd *pw;
673 size_t len;
674 ...
675 // digits required for pid_t is number of bits times
676 // log2(10) = approx 10/33
677 len = strlen(pw->pw_dir) + 1 + 1+(sizeof(pid_t)*80+32)/33 +
678 sizeof ".out";
679 pathname = malloc(len);
680 if (pathname != NULL)
681 {
682 snprintf(pathname, len, "%s/%jd.out", pw->pw_dir,
683 (intmax_t)getpid());
684 ...
685 }
686
687 Reporting an Event
688 The following example loops until an event has timed out. The pause()
689 function waits forever unless it receives a signal. The fprintf()
690 statement should never occur due to the possible return values of
691 pause().
692
693 #include <stdio.h>
694 #include <unistd.h>
695 #include <string.h>
696 #include <errno.h>
697 ...
698 while (!event_complete) {
699 ...
700 if (pause() != −1 || errno != EINTR)
701 fprintf(stderr, "pause: unknown error: %s\n", strerror(errno));
702 }
703 ...
704
705 Printing Monetary Information
706 The following example uses strfmon() to convert a number and store it
707 as a formatted monetary string named convbuf. If the first number is
708 printed, the program prints the format and the description; otherwise,
709 it just prints the number.
710
711 #include <monetary.h>
712 #include <stdio.h>
713 ...
714 struct tblfmt {
715 char *format;
716 char *description;
717 };
718
719 struct tblfmt table[] = {
720 { "%n", "default formatting" },
721 { "%11n", "right align within an 11 character field" },
722 { "%#5n", "aligned columns for values up to 99999" },
723 { "%=*#5n", "specify a fill character" },
724 { "%=0#5n", "fill characters do not use grouping" },
725 { "%^#5n", "disable the grouping separator" },
726 { "%^#5.0n", "round off to whole units" },
727 { "%^#5.4n", "increase the precision" },
728 { "%(#5n", "use an alternative pos/neg style" },
729 { "%!(#5n", "disable the currency symbol" },
730 };
731 ...
732 float input[3];
733 int i, j;
734 char convbuf[100];
735 ...
736 strfmon(convbuf, sizeof(convbuf), table[i].format, input[j]);
737
738 if (j == 0) {
739 printf("%s%s%s\n", table[i].format,
740 convbuf, table[i].description);
741 }
742 else {
743 printf("%s\n", convbuf);
744 }
745 ...
746
747 Printing Wide Characters
748 The following example prints a series of wide characters. Suppose that
749 "L`@`" expands to three bytes:
750
751 wchar_t wz [3] = L"@@"; // Zero-terminated
752 wchar_t wn [3] = L"@@@"; // Unterminated
753
754 fprintf (stdout,"%ls", wz); // Outputs 6 bytes
755 fprintf (stdout,"%ls", wn); // Undefined because wn has no terminator
756 fprintf (stdout,"%4ls", wz); // Outputs 3 bytes
757 fprintf (stdout,"%4ls", wn); // Outputs 3 bytes; no terminator needed
758 fprintf (stdout,"%9ls", wz); // Outputs 6 bytes
759 fprintf (stdout,"%9ls", wn); // Outputs 9 bytes; no terminator needed
760 fprintf (stdout,"%10ls", wz); // Outputs 6 bytes
761 fprintf (stdout,"%10ls", wn); // Undefined because wn has no terminator
762
763 In the last line of the example, after processing three characters,
764 nine bytes have been output. The fourth character must then be examined
765 to determine whether it converts to one byte or more. If it converts to
766 more than one byte, the output is only nine bytes. Since there is no
767 fourth character in the array, the behavior is undefined.
768
770 If the application calling fprintf() has any objects of type wint_t or
771 wchar_t, it must also include the <wchar.h> header to have these
772 objects defined.
773
775 None.
776
778 None.
779
781 Section 2.5, Standard I/O Streams, fputc(), fscanf(), setlocale(),
782 strfmon(), wcrtomb()
783
784 The Base Definitions volume of POSIX.1‐2008, Chapter 7, Locale,
785 <stdio.h>, <wchar.h>
786
788 Portions of this text are reprinted and reproduced in electronic form
789 from IEEE Std 1003.1, 2013 Edition, Standard for Information Technology
790 -- Portable Operating System Interface (POSIX), The Open Group Base
791 Specifications Issue 7, Copyright (C) 2013 by the Institute of Electri‐
792 cal and Electronics Engineers, Inc and The Open Group. (This is
793 POSIX.1-2008 with the 2013 Technical Corrigendum 1 applied.) In the
794 event of any discrepancy between this version and the original IEEE and
795 The Open Group Standard, the original IEEE and The Open Group Standard
796 is the referee document. The original Standard can be obtained online
797 at http://www.unix.org/online.html .
798
799 Any typographical or formatting errors that appear in this page are
800 most likely to have been introduced during the conversion of the source
801 files to man page format. To report such errors, see https://www.ker‐
802 nel.org/doc/man-pages/reporting_bugs.html .
803
804
805
806IEEE/The Open Group 2013 FPRINTF(3P)