xref: /openbsd-src/lib/libc/stdio/printf.3 (revision b2ea75c1b17e1a9a339660e7ed45cd24946b230e)
1.\"	$OpenBSD: printf.3,v 1.35 2001/06/23 15:00:25 provos 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
408and
409.Tn Tahoe
410compilers).
411.It
412A character that specifies the type of conversion to be applied.
413.El
414.Pp
415A field width or precision, or both, may be indicated by
416an asterisk
417.Ql *
418or an asterisk followed by one or more decimal digits and a
419.Ql $
420instead of a
421digit string.
422In this case, an
423.Li int
424argument supplies the field width or precision.
425A negative field width is treated as a left adjustment flag followed by a
426positive field width; a negative precision is treated as though it were
427missing.
428If a single format directive mixes positional (nn$) and
429non-positional arguments, the results are undefined.
430.Pp
431The conversion specifiers and their meanings are:
432.Bl -tag -width "diouxX"
433.It Cm diouxX
434The
435.Li int
436(or appropriate variant) argument is converted to signed decimal
437.Pf ( Cm d
438and
439.Cm i ) ,
440unsigned octal
441.Pq Cm o ,
442unsigned decimal
443.Pq Cm u ,
444or unsigned hexadecimal
445.Pf ( Cm x
446and
447.Cm X )
448notation.
449The letters
450.Cm abcdef
451are used for
452.Cm x
453conversions; the letters
454.Cm ABCDEF
455are used for
456.Cm X
457conversions.
458The precision, if any, gives the minimum number of digits that must
459appear; if the converted value requires fewer digits, it is padded on
460the left with zeros.
461.It Cm DOU
462The
463.Li long int
464argument is converted to signed decimal, unsigned octal, or unsigned
465decimal, as if the format had been
466.Cm ld ,
467.Cm lo ,
468or
469.Cm lu
470respectively.
471These conversion characters are deprecated, and will eventually disappear.
472.It Cm eE
473The
474.Li double
475argument is rounded and converted in the style
476.Sm off
477.Pf [\-]d Cm \&. No ddd Cm e No \\*(Pmdd
478.Sm on
479where there is one digit before the
480decimal-point character
481and the number of digits after it is equal to the precision;
482if the precision is missing,
483it is taken as 6; if the precision is
484zero, no decimal-point character appears.
485An
486.Cm E
487conversion uses the letter
488.Cm E
489(rather than
490.Cm e )
491to introduce the exponent.
492The exponent always contains at least two digits; if the value is zero,
493the exponent is 00.
494.It Cm f
495The
496.Li double
497argument is rounded and converted to decimal notation in the style
498.Sm off
499.Pf [-]ddd Cm \&. No ddd ,
500.Sm on
501where the number of digits after the decimal-point character
502is equal to the precision specification.
503If the precision is missing, it is taken as 6; if the precision is
504explicitly zero, no decimal-point character appears.
505If a decimal point appears, at least one digit appears before it.
506.It Cm gG
507The
508.Li double
509argument is converted in style
510.Cm f
511or
512.Cm e
513(or
514.Cm E
515for
516.Cm G
517conversions).
518The precision specifies the number of significant digits.
519If the precision is missing, 6 digits are given; if the precision is zero,
520it is treated as 1.
521Style
522.Cm e
523is used if the exponent from its conversion is less than -4 or greater than
524or equal to the precision.
525Trailing zeros are removed from the fractional part of the result; a
526decimal point appears only if it is followed by at least one digit.
527.It Cm c
528The
529.Li int
530argument is converted to an
531.Li unsigned char ,
532and the resulting character is written.
533.It Cm s
534The
535.Li char *
536argument is expected to be a pointer to an array of character type (pointer
537to a string).
538Characters from the array are written up to (but not including)
539a terminating
540.Tn NUL
541character;
542if a precision is specified, no more than the number specified are
543written.
544If a precision is given, no null character
545need be present; if the precision is not specified, or is greater than
546the size of the array, the array must contain a terminating
547.Tn NUL
548character.
549.It Cm p
550The
551.Li void *
552pointer argument is printed in hexadecimal (as if by
553.Ql %#x
554or
555.Ql %#lx ) .
556.It Cm n
557The number of characters written so far is stored into the
558integer indicated by the
559.Li int *
560(or variant) pointer argument.
561No argument is converted.
562.It Cm %
563A
564.Ql %
565is written.
566No argument is converted.
567The complete conversion specification is
568.Ql %% .
569.El
570.Pp
571In no case does a non-existent or small field width cause truncation of
572a field; if the result of a conversion is wider than the field width, the
573field is expanded to contain the conversion result.
574.Sh EXAMPLES
575To print a date and time in the form `Sunday, July 3, 10:02',
576where
577.Va weekday
578and
579.Va month
580are pointers to strings:
581.Bd -literal -offset indent
582#include <stdio.h>
583
584fprintf(stdout, "%s, %s %d, %.2d:%.2d\en",
585    weekday, month, day, hour, min);
586.Ed
587.Pp
588To print \*(Pi
589to five decimal places:
590.Bd -literal -offset indent
591#include <math.h>
592#include <stdio.h>
593
594fprintf(stdout, "pi = %.5f\en", 4 * atan(1.0));
595.Ed
596.Pp
597To allocate a 128 byte string and print into it:
598.Bd -literal -offset indent
599#include <stdio.h>
600#include <stdlib.h>
601#include <stdarg.h>
602
603char *
604newfmt(const char *fmt, ...)
605{
606	char *p;
607	va_list ap;
608
609	if ((p = malloc(128)) == NULL)
610		return (NULL);
611	va_start(ap, fmt);
612	(void) vsnprintf(p, 128, fmt, ap);
613	va_end(ap);
614	return (p);
615}
616.Ed
617.Sh SEE ALSO
618.Xr printf 1 ,
619.Xr scanf 3
620.Sh STANDARDS
621The
622.Fn fprintf ,
623.Fn printf ,
624.Fn sprintf ,
625.Fn vprintf ,
626.Fn vfprintf ,
627and
628.Fn vsprintf
629functions conform to
630.St -ansiC .
631.Sh HISTORY
632The functions
633.Fn snprintf
634and
635.Fn vsnprintf
636first appeared in
637.Bx 4.4 .
638.Pp
639The functions
640.Fn asprintf
641and
642.Fn vasprintf
643first appeared in the GNU C library.
644This implementation first appeared in
645.Ox 2.3 .
646.Sh CAVEATS
647The conversion formats
648.Cm \&%D ,
649.Cm \&%O ,
650and
651.Cm %U
652are not standard and
653are provided only for backward compatibility.
654The effect of padding the
655.Cm %p
656format with zeros (either by the
657.Sq Cm 0
658flag or by specifying a precision), and the benign effect (i.e., none)
659of the
660.Sq Cm #
661flag on
662.Cm %n
663and
664.Cm %p
665conversions, as well as other
666nonsensical combinations such as
667.Cm %Ld ,
668are not standard; such combinations
669should be avoided.
670.Pp
671Because
672.Fn sprintf
673and
674.Fn vsprintf
675assume an infinitely long string,
676callers must be careful not to overflow the actual space;
677this is often impossible to assure.
678For safety, programmers should use the
679.Fn snprintf
680and
681.Fn asprintf
682family of interfaces instead.
683Unfortunately, the
684.Fn snprintf
685interface is not available on older
686systems and the
687.Fn asprintf
688interface is not portable.
689.Pp
690It is important never to pass a string with user-supplied data as a
691format without using
692.Ql %s .
693An attacker can put format specifiers in the string to mangle your stack,
694leading to a possible security hole.
695This holds true even if you have built the string
696.Dq by hand
697using a function like
698.Fn snprintf ,
699as the resulting string may still contain user-supplied conversion specifiers
700for later interpolation by
701.Fn printf .
702.Pp
703Be sure to use the proper secure idiom:
704.Bd -literal -offset indent
705snprintf(buffer, sizeof(buffer), "%s", string);
706.Ed
707.Pp
708There is no way for printf to know the size of each argument passed.
709If you use positional arguments you must ensure that all parameters, up to the
710last positionally specified parameter, are used in the format string.
711This allows for the format string to be parsed for this information.
712Failure to do this will mean your code is non-portable and liable to fail.
713