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