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