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