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