xref: /openbsd/lib/libc/stdio/printf.3 (revision 898184e3)
1.\"	$OpenBSD: printf.3,v 1.61 2013/03/04 01:50:01 brad Exp $
2.\"
3.\" Copyright (c) 1990, 1991, 1993
4.\"	The Regents of the University of California.  All rights reserved.
5.\"
6.\" This code is derived from software contributed to Berkeley by
7.\" Chris Torek and the American National Standards Committee X3,
8.\" on Information Processing Systems.
9.\"
10.\" Redistribution and use in source and binary forms, with or without
11.\" modification, are permitted provided that the following conditions
12.\" are met:
13.\" 1. Redistributions of source code must retain the above copyright
14.\"    notice, this list of conditions and the following disclaimer.
15.\" 2. Redistributions in binary form must reproduce the above copyright
16.\"    notice, this list of conditions and the following disclaimer in the
17.\"    documentation and/or other materials provided with the distribution.
18.\" 3. Neither the name of the University nor the names of its contributors
19.\"    may be used to endorse or promote products derived from this software
20.\"    without specific prior written permission.
21.\"
22.\" THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
23.\" ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
24.\" IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
25.\" ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
26.\" FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
27.\" DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
28.\" OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
29.\" HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
30.\" LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
31.\" OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
32.\" SUCH DAMAGE.
33.\"
34.\"     @(#)printf.3	8.1 (Berkeley) 6/4/93
35.\"
36.Dd $Mdocdate: March 4 2013 $
37.Dt PRINTF 3
38.Os
39.Sh NAME
40.Nm printf ,
41.Nm fprintf ,
42.Nm sprintf ,
43.Nm snprintf ,
44.Nm asprintf ,
45.Nm dprintf ,
46.Nm vprintf ,
47.Nm vfprintf ,
48.Nm vsprintf ,
49.Nm vsnprintf ,
50.Nm vasprintf ,
51.Nm vdprintf
52.Nd formatted output conversion
53.Sh SYNOPSIS
54.Fd #include <stdio.h>
55.Ft int
56.Fn printf "const char *format" ...
57.Ft int
58.Fn fprintf "FILE *stream" "const char *format" ...
59.Ft int
60.Fn sprintf "char *str" "const char *format" ...
61.Ft int
62.Fn snprintf "char *str" "size_t size" "const char *format" ...
63.Ft int
64.Fn asprintf "char **ret" "const char *format" ...
65.Ft int
66.Fn dprintf "int fd" "const char * restrict format" ...
67.Fd #include <stdarg.h>
68.Ft int
69.Fn vprintf "const char *format" "va_list ap"
70.Ft int
71.Fn vfprintf "FILE *stream" "const char *format" "va_list ap"
72.Ft int
73.Fn vsprintf "char *str" "const char *format" "va_list ap"
74.Ft int
75.Fn vsnprintf "char *str" "size_t size" "const char *format" "va_list ap"
76.Ft int
77.Fn vasprintf "char **ret" "const char *format" "va_list ap"
78.Ft int
79.Fn vdprintf "int fd" "const char * restrict format" "va_list ap"
80.Sh DESCRIPTION
81The
82.Fn printf
83family of functions produce output according to the given
84.Fa format
85as described below.
86This format may contain
87.Dq conversion specifiers ;
88the results of such conversions, if any, depend on the arguments
89following the
90.Fa format
91string.
92.Pp
93The
94.Fn printf
95and
96.Fn vprintf
97functions write output to the standard output stream,
98.Em stdout ;
99.Fn fprintf
100and
101.Fn vfprintf
102write output to the supplied stream pointer
103.Fa stream ;
104.Fn dprintf
105and
106.Fn vdprintf
107write output to the given file descriptor;
108.Fn sprintf ,
109.Fn snprintf ,
110.Fn vsprintf ,
111and
112.Fn vsnprintf
113write to the character string
114.Fa str ;
115.Fn asprintf
116and
117.Fn vasprintf
118write to a dynamically allocated string that is stored in
119.Fa ret .
120.Pp
121These functions write the output under the control of a
122.Fa format
123string that specifies how subsequent arguments
124(or arguments accessed via the variable-length argument facilities of
125.Xr stdarg 3 )
126are converted for output.
127.Pp
128.Fn snprintf
129and
130.Fn vsnprintf
131will write at most
132.Fa size Ns \-1
133of the characters printed into the output string
134(the
135.Fa size Ns 'th
136character then gets the terminating
137.Ql \e0 ) ;
138if the return value is greater than or equal to the
139.Fa size
140argument, the string was too short
141and some of the printed characters were discarded.
142If
143.Fa size
144is zero,
145.Fa str
146may be a null pointer and no characters will be written;
147the number of bytes that would have been written excluding the terminating
148.Ql \e0
149byte, or \-1 on error, will be returned.
150.Pp
151.Fn sprintf
152and
153.Fn vsprintf
154effectively assume an infinite
155.Fa size .
156.Pp
157The format string is composed of zero or more directives:
158ordinary
159.\" multibyte
160characters (not
161.Cm % ) ,
162which are copied unchanged to the output stream,
163and conversion specifications, each of which results
164in fetching zero or more subsequent arguments.
165Each conversion specification is introduced by the character
166.Cm % .
167The arguments must correspond properly (after type promotion)
168with the conversion specifier.
169After the
170.Cm % ,
171the following appear in sequence:
172.Bl -bullet
173.It
174An optional field, consisting of a decimal digit string followed by a
175.Cm $
176specifying the next argument to access.
177If this field is not provided, the argument following the last
178argument accessed will be used.
179Arguments are numbered starting at
180.Cm 1 .
181.It
182Zero or more of the following flags:
183.Bl -hyphen
184.It
185A hash
186.Sq Cm #
187character
188specifying that the value should be converted to an ``alternate form''.
189For
190.Cm c ,
191.Cm d ,
192.Cm i ,
193.Cm n ,
194.Cm p ,
195.Cm s ,
196and
197.Cm u
198conversions, this option has no effect.
199For
200.Cm o
201conversions, the precision of the number is increased to force the first
202character of the output string to a zero (except if a zero value is printed
203with an explicit precision of zero).
204For
205.Cm x
206and
207.Cm X
208conversions, a non-zero result has the string
209.Ql 0x
210(or
211.Ql 0X
212for
213.Cm X
214conversions) prepended to it.
215For
216.Cm a ,
217.Cm A ,
218.Cm e ,
219.Cm E ,
220.Cm f ,
221.Cm F ,
222.Cm g ,
223and
224.Cm G
225conversions, the result will always contain a decimal point, even if no
226digits follow it (normally, a decimal point appears in the results of
227those conversions only if a digit follows).
228For
229.Cm g
230and
231.Cm G
232conversions, trailing zeros are not removed from the result as they
233would otherwise be.
234.It
235A zero
236.Sq Cm \&0
237character specifying zero padding.
238For all conversions except
239.Cm n ,
240the converted value is padded on the left with zeros rather than blanks.
241If a precision is given with a numeric conversion
242.Pf ( Cm d ,
243.Cm i ,
244.Cm o ,
245.Cm u ,
246.Cm x ,
247and
248.Cm X ) ,
249the
250.Sq Cm \&0
251flag is ignored.
252.It
253A negative field width flag
254.Sq Cm \-
255indicates the converted value is to be left adjusted on the field boundary.
256Except for
257.Cm n
258conversions, the converted value is padded on the right with blanks,
259rather than on the left with blanks or zeros.
260A
261.Sq Cm \-
262overrides a
263.Sq Cm \&0
264if both are given.
265.It
266A space, specifying that a blank should be left before a positive number
267produced by a signed conversion
268.Pf ( Cm d ,
269.Cm a ,
270.Cm A ,
271.Cm e ,
272.Cm E ,
273.Cm f ,
274.Cm F ,
275.Cm g ,
276.Cm G ,
277or
278.Cm i ) .
279.It
280A
281.Sq Cm +
282character specifying that a sign always be placed before a
283number produced by a signed conversion.
284A
285.Sq Cm +
286overrides a space if both are used.
287.El
288.It
289An optional decimal digit string specifying a minimum field width.
290If the converted value has fewer characters than the field width, it will
291be padded with spaces on the left (or right, if the left-adjustment
292flag has been given) to fill out
293the field width.
294.It
295An optional precision, in the form of a period
296.Sq Cm \&.
297followed by an
298optional digit string.
299If the digit string is omitted, the precision is taken as zero.
300This gives the minimum number of digits to appear for
301.Cm d ,
302.Cm i ,
303.Cm o ,
304.Cm u ,
305.Cm x ,
306and
307.Cm X
308conversions, the number of digits to appear after the decimal-point for
309.Cm a ,
310.Cm A ,
311.Cm e ,
312.Cm E ,
313.Cm f ,
314and
315.Cm F
316conversions, the maximum number of significant digits for
317.Cm g
318and
319.Cm G
320conversions, or the maximum number of characters to be printed from a
321string for
322.Cm s
323conversions.
324.It
325An optional length modifier, that specifies the size of the argument.
326The following length modifiers are valid for the
327.Cm d , i , n ,
328.Cm o , u , x ,
329or
330.Cm X
331conversion:
332.Bl -column "(deprecated)" "signed char" "unsigned long long" "long long *"
333.It Sy Modifier Ta Sy "d, i" Ta Sy "o, u, x, X" Ta Sy n
334.It hh Ta "signed char" Ta "unsigned char" Ta "signed char *"
335.It h Ta short Ta "unsigned short" Ta "short *"
336.It "l (ell)" Ta long Ta "unsigned long" Ta "long *"
337.It "ll (ell ell)" Ta "long long" Ta "unsigned long long" Ta "long long *"
338.It j Ta intmax_t Ta uintmax_t Ta "intmax_t *"
339.It t Ta ptrdiff_t Ta (see note) Ta "ptrdiff_t *"
340.It z Ta "(see note)" Ta size_t Ta "(see note)"
341.It "q (deprecated)" Ta quad_t Ta u_quad_t Ta "quad_t *"
342.El
343.Pp
344Note:
345the
346.Cm t
347modifier, when applied to an
348.Cm o , u , x ,
349or
350.Cm X
351conversion, indicates that the argument is of an unsigned type
352equivalent in size to a
353.Vt ptrdiff_t .
354The
355.Cm z
356modifier, when applied to a
357.Cm d
358or
359.Cm i
360conversion, indicates that the argument is of a signed type equivalent in
361size to a
362.Vt size_t .
363Similarly, when applied to an
364.Cm n
365conversion, it indicates that the argument is a pointer to a signed type
366equivalent in size to a
367.Vt size_t .
368.Pp
369The following length modifier is valid for the
370.Cm a ,
371.Cm A ,
372.Cm e ,
373.Cm E ,
374.Cm f ,
375.Cm F ,
376.Cm g ,
377or
378.Cm G
379conversion:
380.Bl -column "Modifier" "e, E, f, F, g, G"
381.It Sy Modifier Ta Sy "e, E, f, F, g, G"
382.It "l (ell)" Ta double (ignored: same behavior as without it)
383.It L Ta "long double"
384.El
385.Pp
386The following length modifier is valid for the
387.Cm c
388or
389.Cm s
390conversion:
391.Bl -column "Modifier" "wint_t" "wchar_t *"
392.It Sy Modifier Ta Sy c Ta Sy s
393.It "l (ell)" Ta wint_t Ta "wchar_t *"
394.El
395.It
396A character that specifies the type of conversion to be applied.
397.El
398.Pp
399A field width or precision, or both, may be indicated by
400an asterisk
401.Ql *
402or an asterisk followed by one or more decimal digits and a
403.Ql $
404instead of a
405digit string.
406In this case, an
407.Li int
408argument supplies the field width or precision.
409A negative field width is treated as a left adjustment flag followed by a
410positive field width; a negative precision is treated as though it were
411missing.
412If a single format directive mixes positional (nn$) and
413non-positional arguments, the results are undefined.
414.Pp
415The conversion specifiers and their meanings are:
416.Bl -tag -width "diouxX"
417.It Cm diouxX
418The
419.Li int
420(or appropriate variant) argument is converted to signed decimal
421.Pf ( Cm d
422and
423.Cm i ) ,
424unsigned octal
425.Pq Cm o ,
426unsigned decimal
427.Pq Cm u ,
428or unsigned hexadecimal
429.Pf ( Cm x
430and
431.Cm X )
432notation.
433The letters
434.Cm abcdef
435are used for
436.Cm x
437conversions; the letters
438.Cm ABCDEF
439are used for
440.Cm X
441conversions.
442The precision, if any, gives the minimum number of digits that must
443appear; if the converted value requires fewer digits, it is padded on
444the left with zeros.
445.It Cm DOU
446The
447.Li long int
448argument is converted to signed decimal, unsigned octal, or unsigned
449decimal, as if the format had been
450.Cm ld ,
451.Cm lo ,
452or
453.Cm lu
454respectively.
455These conversion characters are deprecated, and will eventually disappear.
456.It Cm eE
457The
458.Li double
459argument is rounded and converted in the style
460.Sm off
461.Pf [\-]d Cm \&. No ddd Cm e No \*(Pmdd
462.Sm on
463where there is one digit before the
464decimal-point character
465and the number of digits after it is equal to the precision;
466if the precision is missing,
467it is taken as 6; if the precision is
468zero, no decimal-point character appears.
469An
470.Cm E
471conversion uses the letter
472.Cm E
473(rather than
474.Cm e )
475to introduce the exponent.
476The exponent always contains at least two digits; if the value is zero,
477the exponent is 00.
478.Pp
479If the argument is infinity, it will be converted to [-]inf
480.Pq Cm e
481or [-]INF
482.Pq Cm E ,
483respectively.
484If the argument is not-a-number (NaN), it will be converted to
485[-]nan
486.Pq Cm e
487or [-]NAN
488.Pq Cm E ,
489respectively.
490.It Cm fF
491The
492.Li double
493argument is rounded and converted to decimal notation in the style
494.Sm off
495.Pf [-]ddd Cm \&. No ddd ,
496.Sm on
497where the number of digits after the decimal-point character
498is equal to the precision specification.
499If the precision is missing, it is taken as 6; if the precision is
500explicitly zero, no decimal-point character appears.
501If a decimal point appears, at least one digit appears before it.
502.Pp
503If the argument is infinity, it will be converted to [-]inf
504.Pq Cm f
505or [-]INF
506.Pq Cm F ,
507respectively.
508If the argument is not-a-number (NaN), it will be converted to
509[-]nan
510.Pq Cm f
511or [-]NAN
512.Pq Cm F ,
513respectively.
514.It Cm gG
515The
516.Li double
517argument is converted in style
518.Cm f
519or
520.Cm e
521(or
522.Cm E
523for
524.Cm G
525conversions).
526The precision specifies the number of significant digits.
527If the precision is missing, 6 digits are given; if the precision is zero,
528it is treated as 1.
529Style
530.Cm e
531is used if the exponent from its conversion is less than -4 or greater than
532or equal to the precision.
533Trailing zeros are removed from the fractional part of the result; a
534decimal point appears only if it is followed by at least one digit.
535.Pp
536If the argument is infinity, it will be converted to [-]inf
537.Pq Cm g
538or [-]INF
539.Pq Cm G ,
540respectively.
541If the argument is not-a-number (NaN), it will be converted to
542[-]nan
543.Pq Cm g
544or [-]NAN
545.Pq Cm G ,
546respectively.
547.It Cm aA
548The
549.Li double
550argument is rounded and converted to hexadecimal notation in the style
551.Sm off
552.Pf [\-]0xh Cm \&. No hhh Cm p No [\*(Pm]d
553.Sm on
554where the number of digits after the hexadecimal-point character
555is equal to the precision specification.
556If the precision is missing, it is taken as enough to represent
557the floating-point number exactly, and no rounding occurs.
558If the precision is zero, no hexadecimal-point character appears.
559The
560.Cm p
561is a literal character
562.Ql p ,
563and the exponent consists of a positive or negative sign
564followed by a decimal number representing an exponent of 2.
565The
566.Cm A
567conversion uses the prefix
568.Dq Li 0X
569(rather than
570.Dq Li 0x ) ,
571the letters
572.Dq Li ABCDEF
573(rather than
574.Dq Li abcdef )
575to represent the hex digits, and the letter
576.Ql P
577(rather than
578.Ql p )
579to separate the mantissa and exponent.
580.Pp
581Note that there may be multiple valid ways to represent floating-point
582numbers in this hexadecimal format.
583For example,
584.Li 0x3.24p+0 , 0x6.48p-1
585and
586.Li 0xc.9p-2
587are all equivalent.
588The format chosen depends on the internal representation of the
589number, but the implementation guarantees that the length of the
590mantissa will be minimized.
591Zeroes are always represented with a mantissa of 0 (preceded by a
592.Ql -
593if appropriate) and an exponent of
594.Li +0 .
595.Pp
596If the argument is infinity, it will be converted to [-]inf
597.Pq Cm a
598or [-]INF
599.Pq Cm A ,
600respectively.
601If the argument is not-a-number (NaN), it will be converted to
602[-]nan
603.Pq Cm a
604or [-]NAN
605.Pq Cm A ,
606respectively.
607.It Cm c
608The
609.Li int
610argument is converted to an
611.Li unsigned char ,
612and the resulting character is written.
613.It Cm s
614The
615.Li char *
616argument is expected to be a pointer to an array of character type (pointer
617to a string).
618Characters from the array are written up to (but not including)
619a terminating
620.Tn NUL
621character;
622if a precision is specified, no more than the number specified are
623written.
624If a precision is given, no NUL character
625need be present; if the precision is not specified, or is greater than
626the size of the array, the array must contain a terminating
627.Tn NUL
628character.
629.It Cm p
630The
631.Li void *
632pointer argument is printed in hexadecimal (as if by
633.Ql %#x
634or
635.Ql %#lx ) .
636.It Cm n
637The number of characters written so far is stored into the
638integer indicated by the
639.Li int *
640(or variant) pointer argument.
641No argument is converted.
642.It Cm %
643A
644.Ql %
645is written.
646No argument is converted.
647The complete conversion specification is
648.Ql %% .
649.El
650.Pp
651In no case does a non-existent or small field width cause truncation of
652a field; if the result of a conversion is wider than the field width, the
653field is expanded to contain the conversion result.
654.Sh RETURN VALUES
655For all these functions if an output or encoding error occurs, a value
656of \-1 is returned.
657.Pp
658The
659.Fn printf ,
660.Fn fprintf ,
661.Fn sprintf ,
662.Fn vprintf ,
663.Fn vfprintf ,
664.Fn vsprintf ,
665.Fn asprintf ,
666and
667.Fn vasprintf
668functions
669return the number of characters printed
670(not including the trailing
671.Ql \e0
672used to end output to strings).
673.Pp
674The
675.Fn snprintf
676and
677.Fn vsnprintf
678functions return the number of characters that would have
679been output if the
680.Fa size
681were unlimited
682.Po
683again, not including the final
684.Ql \e0 .
685.Pc .
686.Pp
687The
688.Fn asprintf
689and
690.Fn vasprintf
691functions return the number of characters that were output
692to the newly allocated string
693(excluding the final
694.Ql \e0 ) .
695A pointer to the newly allocated string is returned in
696.Fa ret ;
697it should be passed to
698.Xr free 3
699to release the allocated storage
700when it is no longer needed.
701If sufficient space cannot be allocated, these functions
702will return \-1.
703The value of
704.Fa ret
705in this situation is implementation-dependent
706(on
707.Ox ,
708.Fa ret
709will be set to the null pointer, but this behavior should not be relied upon).
710.Sh EXAMPLES
711To print a date and time in the form `Sunday, July 3, 10:02',
712where
713.Va weekday
714and
715.Va month
716are pointers to strings:
717.Bd -literal -offset indent
718#include <stdio.h>
719
720fprintf(stdout, "%s, %s %d, %.2d:%.2d\en",
721    weekday, month, day, hour, min);
722.Ed
723.Pp
724To print \*(Pi
725to five decimal places:
726.Bd -literal -offset indent
727#include <math.h>
728#include <stdio.h>
729
730fprintf(stdout, "pi = %.5f\en", 4 * atan(1.0));
731.Ed
732.Pp
733To allocate a 128-byte string and print into it:
734.Bd -literal -offset indent
735#include <stdarg.h>
736#include <stdio.h>
737#include <stdlib.h>
738
739char *
740newfmt(const char *fmt, ...)
741{
742	char *p;
743	va_list ap;
744
745	if ((p = malloc(128)) == NULL)
746		return (NULL);
747	va_start(ap, fmt);
748	(void) vsnprintf(p, 128, fmt, ap);
749	va_end(ap);
750	return (p);
751}
752.Ed
753.Sh SEE ALSO
754.Xr printf 1 ,
755.Xr scanf 3
756.Sh STANDARDS
757The
758.Fn fprintf ,
759.Fn printf ,
760.Fn snprintf ,
761.Fn sprintf ,
762.Fn vfprintf ,
763.Fn vprintf ,
764.Fn vsnprintf ,
765and
766.Fn vsprintf
767functions conform to
768.St -isoC-99 .
769The
770.Fn dprintf
771and
772.Fn vdprintf
773functions conform to
774.St -p1003.1-2008 .
775.Sh HISTORY
776The functions
777.Fn snprintf
778and
779.Fn vsnprintf
780first appeared in
781.Bx 4.4 .
782.Pp
783The functions
784.Fn asprintf
785and
786.Fn vasprintf
787first appeared in the GNU C library.
788This implementation first appeared in
789.Ox 2.3 .
790.Pp
791The functions
792.Fn dprintf
793and
794.Fn vdprintf
795first appeared in
796.Ox 5.3 .
797.Sh CAVEATS
798The conversion formats
799.Cm \&%D ,
800.Cm \&%O ,
801and
802.Cm %U
803are not standard and
804are provided only for backward compatibility.
805The effect of padding the
806.Cm %p
807format with zeros (either by the
808.Sq Cm 0
809flag or by specifying a precision), and the benign effect (i.e., none)
810of the
811.Sq Cm #
812flag on
813.Cm %n
814and
815.Cm %p
816conversions, as well as other
817nonsensical combinations such as
818.Cm %Ld ,
819are not standard; such combinations
820should be avoided.
821.Pp
822Because
823.Fn sprintf
824and
825.Fn vsprintf
826assume an infinitely long string,
827callers must be careful not to overflow the actual space;
828this is often impossible to assure.
829For safety, programmers should use the
830.Fn snprintf
831and
832.Fn asprintf
833family of interfaces instead.
834Unfortunately, the
835.Fn snprintf
836interface is not available on older
837systems and the
838.Fn asprintf
839interface is not portable.
840.Pp
841It is important never to pass a string with user-supplied data as a
842format without using
843.Ql %s .
844An attacker can put format specifiers in the string to mangle the stack,
845leading to a possible security hole.
846This holds true even if the string has been built
847.Dq by hand
848using a function like
849.Fn snprintf ,
850as the resulting string may still contain user-supplied conversion specifiers
851for later interpolation by
852.Fn printf .
853.Pp
854Be sure to use the proper secure idiom:
855.Bd -literal -offset indent
856snprintf(buffer, sizeof(buffer), "%s", string);
857.Ed
858.Pp
859There is no way for
860.Fn printf
861to know the size of each argument passed.
862If positional arguments are used, care must be taken to ensure that all
863parameters, up to the
864last positionally specified parameter, are used in the format string.
865This allows for the format string to be parsed for this information.
866Failure to do this will mean the code is non-portable and liable to fail.
867