xref: /netbsd-src/lib/libc/stdio/printf.3 (revision 23c8222edbfb0f0932d88a8351d3a0cf817dfb9e)
1.\"	$NetBSD: printf.3,v 1.38 2003/09/08 17:54:32 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. 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 May 11, 2003
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
376The optional character
377.Cm q ,
378or alternatively two consecutive
379.Cm l
380(ell) characters,
381specifying that a following
382.Cm d ,
383.Cm i ,
384.Cm o ,
385.Cm u ,
386.Cm x ,
387or
388.Cm X
389conversion corresponds to a
390.Em quad_t
391or
392.Em u_quad_t
393argument, or that a following
394.Cm n
395conversion corresponds to a pointer to a
396.Em quad_t
397argument.
398.It
399The optional character
400.Cm t ,
401specifying that a following
402.Cm d ,
403.Cm i ,
404.Cm o ,
405.Cm u ,
406.Cm x ,
407or
408.Cm X
409conversion corresponds to a
410.Em ptrdiff_t
411or
412the corresponding unsigned integer type
413argument, or that a following
414.Cm n
415conversion corresponds to a pointer to a
416.Em ptrdiff_t
417argument.
418.It
419The optional character
420.Cm z ,
421specifying that a following
422.Cm d ,
423.Cm i ,
424.Cm o ,
425.Cm u ,
426.Cm x ,
427or
428.Cm X
429conversion corresponds to a
430.Em size_t
431or
432the corresponding signed integer type
433argument, or that a following
434.Cm n
435conversion corresponds to a pointer to a
436signed integer type corresponding to
437.Em size_t
438argument.
439.It
440The character
441.Cm L
442specifying that a following
443.Cm e ,
444.Cm E ,
445.Cm f ,
446.Cm F ,
447.Cm g ,
448or
449.Cm G
450conversion corresponds to a
451.Em long double
452argument.
453.It
454A character that specifies the type of conversion to be applied.
455.El
456.Pp
457A field width or precision, or both, may be indicated by
458an asterisk
459.Ql *
460instead of a digit string.
461In this case, an
462.Em int
463argument supplies the field width or precision.
464A negative field width is treated as a left adjustment flag followed by a
465positive field width; a negative precision is treated as though it were
466missing.
467.Pp
468The conversion specifiers and their meanings are:
469.Bl -tag -width "diouxX"
470.It Cm diouxX
471The
472.Em int
473(or appropriate variant) argument is converted to signed decimal
474.Pf ( Cm d
475and
476.Cm i ) ,
477unsigned octal
478.Pq Cm o ,
479unsigned decimal
480.Pq Cm u ,
481or unsigned hexadecimal
482.Pf ( Cm x
483and
484.Cm X )
485notation.
486The letters
487.Cm abcdef
488are used for
489.Cm x
490conversions; the letters
491.Cm ABCDEF
492are used for
493.Cm X
494conversions.
495The precision, if any, gives the minimum number of digits that must
496appear; if the converted value requires fewer digits, it is padded on
497the left with zeros.
498.It Cm DOU
499The
500.Em long int
501argument is converted to signed decimal, unsigned octal, or unsigned
502decimal, as if the format had been
503.Cm ld ,
504.Cm lo ,
505or
506.Cm lu
507respectively.
508These conversion characters are deprecated, and will eventually disappear.
509.It Cm fF
510The
511.Em double
512argument is rounded and converted to decimal notation in the style
513.Sm off
514.Pf [-]ddd Cm \&. No ddd ,
515.Sm on
516where the number of digits after the decimal-point character
517is equal to the precision specification.
518If the precision is missing, it is taken as 6; if the precision is
519explicitly zero, no decimal-point character appears.
520If a decimal point appears, at least one digit appears before it.
521.Pp
522If the double argument represents an infinity it is converted
523in the style
524.Pf [-] Cm inf .
525If the double argument represents a NaN it is converted
526in the style
527.Pf [-] Cm nan .
528An
529.Cm F
530conversion produces
531.Pf [-] Cm INF
532and
533.Pf [-] Cm NAN ,
534respectively.
535.It Cm eE
536The
537.Em double
538argument is rounded and converted in the style
539.Sm off
540.Pf [\-]d Cm \&. No ddd Cm e No \\*(Pmdd
541.Sm on
542where there is one digit before the
543decimal-point character
544and the number of digits after it is equal to the precision;
545if the precision is missing,
546it is taken as 6; if the precision is
547zero, no decimal-point character appears.
548An
549.Cm E
550conversion uses the letter
551.Cm E
552(rather than
553.Cm e )
554to introduce the exponent.
555The exponent always contains at least two digits; if the value is zero,
556the exponent is 00.
557.Pp
558Double arguments representing infinities or NaNs are converted in the
559same styles as in the
560.Cm f
561and
562.Cm F
563conversions.
564.It Cm gG
565The
566.Em double
567argument is converted in style
568.Cm f
569or
570.Cm e
571(or in style
572.Cm F
573or
574.Cm E
575for
576.Cm G
577conversions).
578The precision specifies the number of significant digits.
579If the precision is missing, 6 digits are given; if the precision is zero,
580it is treated as 1.
581Style
582.Cm e
583is used if the exponent from its conversion is less than -4 or greater than
584or equal to the precision.
585Trailing zeros are removed from the fractional part of the result; a
586decimal point appears only if it is followed by at least one digit.
587.Pp
588Double arguments representing infinities or NaNs are converted in the
589same styles as in the
590.Cm f
591and
592.Cm F
593conversions.
594.It Cm c
595The
596.Em int
597argument is converted to an
598.Em unsigned char ,
599and the resulting character is written.
600.It Cm s
601The
602.Dq Em char *
603argument is expected to be a pointer to an array of character type (pointer
604to a string).
605Characters from the array are written up to (but not including)
606a terminating
607.Dv NUL
608character;
609if a precision is specified, no more than the number specified are
610written.
611If a precision is given, no null character
612need be present; if the precision is not specified, or is greater than
613the size of the array, the array must contain a terminating
614.Dv NUL
615character.
616.It Cm p
617The
618.Dq Em void *
619pointer argument is printed in hexadecimal (as if by
620.Ql %#x
621or
622.Ql %#lx ) .
623.It Cm n
624The number of characters written so far is stored into the
625integer indicated by the
626.Dq Em int *
627(or variant) pointer argument.
628No argument is converted.
629.It Cm %
630A
631.Ql %
632is written.
633No argument is converted.
634The complete conversion specification is
635.Ql %% .
636.El
637.Pp
638In no case does a non-existent or small field width cause truncation of
639a field; if the result of a conversion is wider than the field width, the
640field is expanded to contain the conversion result.
641.Sh RETURN VALUES
642Upon successful completion
643.Fn printf ,
644.Fn fprintf ,
645.Fn vprintf ,
646and
647.Fn vfprintf
648return the number of characters printed.
649Otherwise \-1 is returned and
650.Dv errno
651is set to indicate the error.
652.Pp
653Upon successful completion
654.Fn sprintf
655and
656.Fn vsprintf
657return the number of characters written to
658.Fa str ,
659excluding the terminating
660.Dv NUL
661character.
662Otherwise \-1 is returned and
663.Dv errno
664is set to indicate the error.
665.Pp
666Upon successful completion
667.Fn snprintf
668and
669.Fn vsnprintf
670return the number of characters that would have been written
671to a sufficiently sized
672.Fa str ,
673excluding the terminating
674.Dv NUL
675character.
676.Pp
677Upon successful completion
678.Fn asprintf
679and
680.Fn vasprintf
681return the number of characters written to
682.Fa ret ,
683excluding the terminating
684.Dv NUL
685character.
686Otherwise \-1 is returned,
687.Fa ret
688is set to
689.Dv NULL ,
690and
691.Dv errno
692is set to indicate the error.
693.Sh EXAMPLES
694.br
695To print a date and time in the form `Sunday, July 3, 10:02',
696where
697.Em weekday
698and
699.Em month
700are pointers to strings:
701.Bd -literal -offset indent
702#include \*[Lt]stdio.h\*[Gt]
703fprintf(stdout, "%s, %s %d, %.2d:%.2d\en",
704	weekday, month, day, hour, min);
705.Ed
706.Pp
707To print \*(Pi
708to five decimal places:
709.Bd -literal -offset indent
710#include \*[Lt]math.h\*[Gt]
711#include \*[Lt]stdio.h\*[Gt]
712fprintf(stdout, "pi = %.5f\en", 4 * atan(1.0));
713.Ed
714.Pp
715To allocate a 128 byte string and print into it:
716.Bd -literal -offset indent
717#include \*[Lt]stdio.h\*[Gt]
718#include \*[Lt]stdlib.h\*[Gt]
719#include \*[Lt]stdarg.h\*[Gt]
720char *newfmt(const char *fmt, ...)
721{
722		char *p;
723		va_list ap;
724		if ((p = malloc(128)) == NULL)
725			return (NULL);
726		va_start(ap, fmt);
727		(void) vsnprintf(p, 128, fmt, ap);
728		va_end(ap);
729		return (p);
730}
731.Ed
732.Sh SEE ALSO
733.Xr printf 1 ,
734.Xr scanf 3 ,
735.Xr printf 9
736.Sh STANDARDS
737The
738.Fn fprintf ,
739.Fn printf ,
740.Fn sprintf ,
741.Fn vprintf ,
742.Fn vfprintf ,
743and
744.Fn vsprintf
745functions
746conform to
747.St -isoC-90 .
748The conversion format modifiers
749.Cm %j ,
750.Cm %t
751and
752.Cm %z
753conform to
754.St -isoC-99 .
755The
756.Fn snprintf
757and
758.Fn vsnprintf
759functions
760conform to
761.St -isoC-99 .
762.Sh HISTORY
763The functions
764.Fn snprintf
765and
766.Fn vsnprintf
767first appeared in
768.Bx 4.4 .
769The functions
770.Fn asprintf
771and
772.Fn vasprintf
773are modeled on the ones that first appeared in the GNU C library.
774.Sh CAVEATS
775Because
776.Fn sprintf
777and
778.Fn vsprintf
779assume an infinitely long string, callers must be careful not to
780overflow the actual space; this is often impossible to assure.
781For safety, programmers should use the
782.Fn snprintf
783and
784.Fn asprintf
785family of interfaces instead.
786Unfortunately, the
787.Fn snprintf
788interfaces are not available on older
789systems and the
790.Fn asprintf
791interfaces are not yet portable.
792.Pp
793It is important never to pass a string with user-supplied data as a
794format without using
795.Ql %s .
796An attacker can put format specifiers in the string to mangle your stack,
797leading to a possible security hole.
798This holds true even if you have built the string
799.Dq by hand
800using a function like
801.Fn snprintf ,
802as the resulting string may still contain user-supplied conversion specifiers
803for later interpolation by
804.Fn printf .
805.Pp
806Be sure to use the proper secure idiom:
807.Bd -literal -offset indent
808snprintf(buffer, sizeof(buffer), "%s", string);
809.Ed
810.Pp
811There is no way for printf to know the size of each argument passed.
812If you use positional arguments you must ensure that all parameters, up to the
813last positionally specified parameter, are used in the format string.
814This allows for the format string to be parsed for this information.
815Failure to do this will mean your code is non-portable and liable to fail.
816.Sh BUGS
817The conversion formats
818.Cm \&%D ,
819.Cm \&%O ,
820and
821.Cm %U
822are not standard and are provided only for backward compatibility.
823The effect of padding the
824.Cm %p
825format with zeros (either by the
826.Sq Cm 0
827flag or by specifying a precision), and the benign effect (i.e. none)
828of the
829.Sq Cm #
830flag on
831.Cm %n
832and
833.Cm %p
834conversions, as well as other nonsensical combinations such as
835.Cm %Ld ,
836are not standard; such combinations should be avoided.
837