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