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