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