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