xref: /freebsd/lib/libc/stdio/printf.3 (revision 5521ff5a4d1929056e7ffc982fac3341ca54df7c)
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 , fprintf , sprintf , snprintf , asprintf ,
44.Nm vprintf , vfprintf, vsprintf , vsnprintf , vasprintf
45.Nd formatted output conversion
46.Sh LIBRARY
47.Lb libc
48.Sh SYNOPSIS
49.Fd #include <stdio.h>
50.Ft int
51.Fn printf "const char *format" ...
52.Ft int
53.Fn fprintf "FILE *stream" "const char *format" ...
54.Ft int
55.Fn sprintf "char *str" "const char *format" ...
56.Ft int
57.Fn snprintf "char *str" "size_t size" "const char *format" ...
58.Ft int
59.Fn asprintf "char **ret" "const char *format" ...
60.Fd #include <stdarg.h>
61.Ft int
62.Fn vprintf "const char *format" "va_list ap"
63.Ft int
64.Fn vfprintf "FILE *stream" "const char *format" "va_list ap"
65.Ft int
66.Fn vsprintf "char *str" "const char *format" "va_list ap"
67.Ft int
68.Fn vsnprintf "char *str" "size_t size" "const char *format" "va_list ap"
69.Ft int
70.Fn vasprintf "char **ret" "const char *format" "va_list ap"
71.Sh DESCRIPTION
72The
73.Fn printf
74family of functions produces output according to a
75.Fa format
76as described below.
77.Fn Printf
78and
79.Fn vprintf
80write output to
81.Pa stdout ,
82the standard output stream;
83.Fn fprintf
84and
85.Fn vfprintf
86write output to the given output
87.Fa stream ;
88.Fn sprintf ,
89.Fn snprintf ,
90.Fn vsprintf ,
91and
92.Fn vsnprintf
93write to the character string
94.Fa str ;
95and
96.Fn asprintf
97and
98.Fn vasprintf
99dynamically allocate a new string with
100.Xr malloc 3 .
101.Pp
102These functions write the output under the control of a
103.Fa format
104string that specifies how subsequent arguments
105(or arguments accessed via the variable-length argument facilities of
106.Xr stdarg 3 )
107are converted for output.
108.Pp
109These functions return the number of characters printed
110(not including the trailing
111.Ql \e0
112used to end output to strings),
113except for
114.Fn snprintf
115and
116.Fn vsnprintf ,
117which return the number of characters that would have been printed if the
118.Fa size
119were unlimited
120(again, not including the final
121.Ql \e0 ) .
122.Pp
123.Fn Asprintf
124and
125.Fn vasprintf
126set
127.Fa *ret
128to be a pointer to a buffer sufficiently large to hold the formatted string.
129This pointer should be passed to
130.Xr free 3
131to release the allocated storage when it is no longer needed.
132If sufficient space cannot be allocated,
133.Fn asprintf
134and
135.Fn vasprintf
136will return -1 and set
137.Fa ret
138to be a
139.Dv NULL
140pointer.
141.Pp
142.Fn Snprintf
143and
144.Fn vsnprintf
145will write at most
146.Fa size Ns \-1
147of the characters printed into the output string
148(the
149.Fa size Ns 'th
150character then gets the terminating
151.Ql \e0 ) ;
152if the return value is greater than or equal to the
153.Fa size
154argument, the string was too short
155and some of the printed characters were discarded.
156The output is always null-terminated.
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
174.Cm %
175character.
176The arguments must correspond properly (after type promotion)
177with the conversion specifier.
178After the
179.Cm % ,
180the following appear in sequence:
181.Bl -bullet
182.It
183An optional field, consisting of a decimal digit string followed by a
184.Cm $ ,
185specifying the next argument to access.
186If this field is not provided, the argument following the last
187argument accessed will be used.
188Arguments are numbered starting at
189.Cm 1 .
190If unaccessed arguments in the format string are interspersed with ones that
191are accessed the results will be indeterminate.
192.It
193Zero or more of the following flags:
194.Bl -hyphen
195.It
196A
197.Cm #
198character
199specifying that the value should be converted to an
200.Dq alternate form .
201For
202.Cm c , d , i , n , p , s ,
203and
204.Cm u
205conversions, this option has no effect.
206For
207.Cm o
208conversions, the precision of the number is increased to force the first
209character of the output string to a zero (except if a zero value is printed
210with an explicit precision of zero).
211For
212.Cm x
213and
214.Cm X
215conversions, a non-zero result has the string
216.Ql 0x
217(or
218.Ql 0X
219for
220.Cm X
221conversions) prepended to it.
222For
223.Cm e , E , f , g ,
224and
225.Cm G
226conversions, the result will always contain a decimal point, even if no
227digits follow it (normally, a decimal point appears in the results of
228those conversions only if a digit follows).
229For
230.Cm g
231and
232.Cm G
233conversions, trailing zeros are not removed from the result as they
234would otherwise be.
235.It
236A
237.Cm 0
238(zero)
239character specifying zero padding.
240For all conversions except
241.Cm n ,
242the converted value is padded on the left with zeros rather than blanks.
243If a precision is given with a numeric conversion
244.Cm ( d , i , o , u , i , x ,
245and
246.Cm X ) ,
247the
248.Cm 0
249flag is ignored.
250.It
251A negative field width flag
252.Cm \-
253indicates the converted value is to be left adjusted on the field boundary.
254Except for
255.Cm n
256conversions, the converted value is padded on the right with blanks,
257rather than on the left with blanks or zeros.
258A
259.Cm \-
260overrides a
261.Cm 0
262if both are given.
263.It
264A space, specifying that a blank should be left before a positive number
265produced by a signed conversion
266.Cm ( d , e , E , f , g , G ,
267or
268.Cm i ) .
269.It
270A
271.Cm +
272character specifying that a sign always be placed before a
273number produced by a signed conversion.
274A
275.Cm +
276overrides a space if both are used.
277.El
278.It
279An optional decimal digit string specifying a minimum field width.
280If the converted value has fewer characters than the field width, it will
281be padded with spaces on the left (or right, if the left-adjustment
282flag has been given) to fill out
283the field width.
284.It
285An optional precision, in the form of a period
286.Cm \&.
287followed by an
288optional digit string.
289If the digit string is omitted, the precision is taken as zero.
290This gives the minimum number of digits to appear for
291.Cm d , i , o , u , x ,
292and
293.Cm X
294conversions, the number of digits to appear after the decimal-point for
295.Cm e , E ,
296and
297.Cm f
298conversions, the maximum number of significant digits for
299.Cm g
300and
301.Cm G
302conversions, or the maximum number of characters to be printed from a
303string for
304.Cm s
305conversions.
306.It
307The optional character
308.Cm h ,
309specifying that a following
310.Cm d , i , o , u , x ,
311or
312.Cm X
313conversion corresponds to a
314.Vt short int
315or
316.Vt unsigned short int
317argument, or that a following
318.Cm n
319conversion corresponds to a pointer to a
320.Vt short int
321argument.
322.It
323The optional character
324.Cm l
325(ell) specifying that a following
326.Cm d , i , o , u , x ,
327or
328.Cm X
329conversion applies to a pointer to a
330.Vt long int
331or
332.Vt unsigned long int
333argument, or that a following
334.Cm n
335conversion corresponds to a pointer to a
336.Vt long int
337argument.
338.It
339The optional characters
340.Cm ll
341(ell ell) specifying that a following
342.Cm d , i , o , u , x ,
343or
344.Cm X
345conversion applies to a pointer to a
346.Vt long long int
347or
348.Vt unsigned long long int
349argument, or that a following
350.Cm n
351conversion corresponds to a pointer to a
352.Vt long long int
353argument.
354.It
355The optional character
356.Cm q ,
357specifying that a following
358.Cm d , i , o , u , x ,
359or
360.Cm X
361conversion corresponds to a
362.Vt quad int
363or
364.Vt unsigned quad int
365argument, or that a following
366.Cm n
367conversion corresponds to a pointer to a
368.Vt quad int
369argument.
370.It
371The character
372.Cm L
373specifying that a following
374.Cm e , E , f , g ,
375or
376.Cm G
377conversion corresponds to a
378.Vt long double
379argument.
380.It
381A character that specifies the type of conversion to be applied.
382.El
383.Pp
384A field width or precision, or both, may be indicated by
385an asterisk
386.Ql *
387or an asterisk followed by one or more decimal digits and a
388.Ql $
389instead of a
390digit string.
391In this case, an
392.Vt int
393argument supplies the field width or precision.
394A negative field width is treated as a left adjustment flag followed by a
395positive field width; a negative precision is treated as though it were
396missing.
397If a single format directive mixes positional (nn$)
398and non-positional arguments, the results are undefined.
399.Pp
400The conversion specifiers and their meanings are:
401.Bl -tag -width "diouxX"
402.It Cm diouxX
403The
404.Vt int
405(or appropriate variant) argument is converted to signed decimal
406.Cm ( d
407and
408.Cm i ) ,
409unsigned octal
410.Pq Cm o ,
411unsigned decimal
412.Pq Cm u ,
413or unsigned hexadecimal
414.Cm ( x
415and
416.Cm X )
417notation.
418The letters
419.Cm abcdef
420are used for
421.Cm x
422conversions; the letters
423.Cm ABCDEF
424are used for
425.Cm X
426conversions.
427The precision, if any, gives the minimum number of digits that must
428appear; if the converted value requires fewer digits, it is padded on
429the left with zeros.
430.It Cm DOU
431The
432.Vt long int
433argument is converted to signed decimal, unsigned octal, or unsigned
434decimal, as if the format had been
435.Cm ld , lo ,
436or
437.Cm lu
438respectively.
439These conversion characters are deprecated, and will eventually disappear.
440.It Cm eE
441The
442.Vt double
443argument is rounded and converted in the style
444.Oo \- Oc Ns d Ns Cm \&. Ns ddd Ns Cm e Ns \\*[Pm]dd
445where there is one digit before the
446decimal-point character
447and the number of digits after it is equal to the precision;
448if the precision is missing,
449it is taken as 6; if the precision is
450zero, no decimal-point character appears.
451An
452.Cm E
453conversion uses the letter
454.Cm E
455(rather than
456.Cm e )
457to introduce the exponent.
458The exponent always contains at least two digits; if the value is zero,
459the exponent is 00.
460.It Cm f
461The
462.Vt double
463argument is rounded and converted to decimal notation in the style
464.Oo \- Oc Ns ddd Ns Cm \&. Ns ddd ,
465where the number of digits after the decimal-point character
466is equal to the precision specification.
467If the precision is missing, it is taken as 6; if the precision is
468explicitly zero, no decimal-point character appears.
469If a decimal point appears, at least one digit appears before it.
470.It Cm gG
471The
472.Vt double
473argument is converted in style
474.Cm f
475or
476.Cm e
477(or
478.Cm E
479for
480.Cm G
481conversions).
482The precision specifies the number of significant digits.
483If the precision is missing, 6 digits are given; if the precision is zero,
484it is treated as 1.
485Style
486.Cm e
487is used if the exponent from its conversion is less than -4 or greater than
488or equal to the precision.
489Trailing zeros are removed from the fractional part of the result; a
490decimal point appears only if it is followed by at least one digit.
491.It Cm c
492The
493.Vt int
494argument is converted to an
495.Vt unsigned char ,
496and the resulting character is written.
497.It Cm s
498The
499.Vt char *
500argument is expected to be a pointer to an array of character type (pointer
501to a string).
502Characters from the array are written up to (but not including)
503a terminating
504.Dv NUL
505character;
506if a precision is specified, no more than the number specified are
507written.
508If a precision is given, no null character
509need be present; if the precision is not specified, or is greater than
510the size of the array, the array must contain a terminating
511.Dv NUL
512character.
513.It Cm p
514The
515.Vt void *
516pointer argument is printed in hexadecimal (as if by
517.Ql %#x
518or
519.Ql %#lx ) .
520.It Cm n
521The number of characters written so far is stored into the
522integer indicated by the
523.Vt int *
524(or variant) pointer argument.
525No argument is converted.
526.It Cm %
527A
528.Ql %
529is written.
530No argument is converted.
531The complete conversion specification
532is
533.Ql %% .
534.El
535.Pp
536The decimal point
537character is defined in the program's locale (category
538.Dv LC_NUMERIC ) .
539.Pp
540In no case does a non-existent or small field width cause truncation of
541a field; if the result of a conversion is wider than the field width, the
542field is expanded to contain the conversion result.
543.Sh EXAMPLES
544To print a date and time in the form
545.Dq Li "Sunday, July 3, 10:02" ,
546where
547.Fa weekday
548and
549.Fa month
550are pointers to strings:
551.Bd -literal -offset indent
552#include <stdio.h>
553fprintf(stdout, "%s, %s %d, %.2d:%.2d\en",
554	weekday, month, day, hour, min);
555.Ed
556.Pp
557To print \*(Pi
558to five decimal places:
559.Bd -literal -offset indent
560#include <math.h>
561#include <stdio.h>
562fprintf(stdout, "pi = %.5f\en", 4 * atan(1.0));
563.Ed
564.Pp
565To allocate a 128 byte string and print into it:
566.Bd -literal -offset indent
567#include <stdio.h>
568#include <stdlib.h>
569#include <stdarg.h>
570char *newfmt(const char *fmt, ...)
571{
572		char *p;
573		va_list ap;
574		if ((p = malloc(128)) == NULL)
575			return (NULL);
576		va_start(ap, fmt);
577		(void) vsnprintf(p, 128, fmt, ap);
578		va_end(ap);
579		return (p);
580}
581.Ed
582.Sh SEE ALSO
583.Xr printf 1 ,
584.Xr scanf 3
585.Sh STANDARDS
586The
587.Fn fprintf ,
588.Fn printf ,
589.Fn sprintf ,
590.Fn vprintf ,
591.Fn vfprintf ,
592and
593.Fn vsprintf
594functions
595conform to
596.St -ansiC
597and
598.St -isoC-99 .
599The
600.Fn snprintf
601and
602.Fn vsnprintf
603functions conform to
604.St -isoC-99 .
605.Sh HISTORY
606The functions
607.Fn asprintf
608and
609.Fn vasprintf
610first appeared in the
611.Tn GNU C
612library.
613These were implemented by
614.An Peter Wemm Aq peter@FreeBSD.org
615in
616.Fx 2.2 ,
617but were later replaced with a different implementation
618from
619.An Todd C. Miller Aq Todd.Miller@courtesan.com
620for
621.Ox 2.3 .
622.Sh BUGS
623The conversion formats
624.Cm \&%D , \&%O ,
625and
626.Cm %U
627are not standard and
628are provided only for backward compatibility.
629The effect of padding the
630.Cm %p
631format with zeros (either by the
632.Cm 0
633flag or by specifying a precision), and the benign effect (i.e., none)
634of the
635.Cm #
636flag on
637.Cm %n
638and
639.Cm %p
640conversions, as well as other
641nonsensical combinations such as
642.Cm %Ld ,
643are not standard; such combinations
644should be avoided.
645.Pp
646Because
647.Fn sprintf
648and
649.Fn vsprintf
650assume an infinitely long string,
651callers must be careful not to overflow the actual space;
652this is often hard to assure.
653For safety, programmers should use the
654.Fn snprintf
655interface instead.
656Unfortunately, this interface was only defined in
657.St -isoC-99 .
658.Pp
659.Cm %n
660can be used to write arbitrary data to the stack.
661Programmers are therefore strongly advised to never pass untrusted strings
662as the
663.Fa format
664argument.
665.Pp
666Never pass a string with user-supplied data as a format without using
667.Ql %s .
668An attacker can put format specifiers in the string to mangle your stack,
669leading to a possible security hole.
670This holds true even if the string was built using a function like
671.Fn snprintf ,
672as the resulting string may still contain user-supplied conversion specifiers
673for later interpolation by
674.Fn printf .
675.Pp
676Always use the proper secure idiom:
677.Pp
678.Dl snprintf(buffer, sizeof(buffer), "%s", string);
679