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