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