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