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