Movatterモバイル変換


[0]ホーム

URL:


man7.org > Linux >man-pages

Linux/UNIX system programming training


printf(3) — Linux manual page

NAME |LIBRARY |SYNOPSIS |DESCRIPTION |RETURN VALUE |ERRORS |ATTRIBUTES |STANDARDS |HISTORY |CAVEATS |BUGS |EXAMPLES |SEE ALSO |COLOPHON

printf(3)                Library Functions Manualprintf(3)

NAME        top

       printf, fprintf, dprintf, sprintf, snprintf, vprintf, vfprintf,       vdprintf, vsprintf, vsnprintf - formatted output conversion

LIBRARY        top

       Standard C library (libc,-lc)

SYNOPSIS        top

#include <stdio.h>int printf(const char *restrictformat, ...);int fprintf(FILE *restrictstream,const char *restrictformat, ...);int dprintf(intfd,const char *restrictformat, ...);int sprintf(char *restrictstr,const char *restrictformat, ...);int snprintf(size_t size;charstr[restrictsize], size_tsize,const char *restrictformat, ...);int vprintf(const char *restrictformat, va_listap);int vfprintf(FILE *restrictstream,const char *restrictformat, va_listap);int vdprintf(intfd,const char *restrictformat, va_listap);int vsprintf(char *restrictstr,const char *restrictformat, va_listap);int vsnprintf(size_t size;charstr[restrictsize], size_tsize,const char *restrictformat, va_listap);   Feature Test Macro Requirements for glibc (seefeature_test_macros(7)):snprintf(),vsnprintf():           _XOPEN_SOURCE >= 500 || _ISOC99_SOURCE               || /* glibc <= 2.19: */ _BSD_SOURCEdprintf(),vdprintf():           Since glibc 2.10:               _POSIX_C_SOURCE >= 200809L           Before glibc 2.10:               _GNU_SOURCE

DESCRIPTION        top

       The functions in theprintf() family produce output according to aformat as described below.  The functionsprintf() andvprintf()       write output tostdout, the standard output stream;fprintf() andvfprintf() write output to the given outputstream;sprintf(),snprintf(),vsprintf(), andvsnprintf() write to the character       stringstr.       The functiondprintf() is the same asfprintf() except that it       outputs to a file descriptor,fd, instead of to astdio(3) stream.       The functionssnprintf() andvsnprintf() write at mostsize bytes       (including the terminating null byte ('\0')) tostr.       The functionsvprintf(),vfprintf(),vdprintf(),vsprintf(),vsnprintf() are equivalent to the functionsprintf(),fprintf(),dprintf(),sprintf(),snprintf(), respectively, except that they       are called with ava_list instead of a variable number of       arguments.  These functions do not call theva_end macro.  Because       they invoke theva_arg macro, the value ofap is undefined after       the call.  Seestdarg(3).       All of these functions write the output under the control of aformat string that specifies how subsequent arguments (or       arguments accessed via the variable-length argument facilities ofstdarg(3)) are converted for output.       C99 and POSIX.1-2001 specify that the results are undefined if a       call tosprintf(),snprintf(),vsprintf(), orvsnprintf() would       cause copying to take place between objects that overlap (e.g., if       the target string array and one of the supplied input arguments       refer to the same buffer).  See CAVEATS.Format of the format string       The format string is a character string, beginning and ending in       its initial shift state, if any.  The format string is composed of       zero or more directives: ordinary characters (not%), which are       copied unchanged to the output stream; and conversion       specifications, each of which results in fetching zero or more       subsequent arguments.  Each conversion specification is introduced       by the character%, and ends with aconversion specifier.  In       between there may be (in this order) zero or moreflags, an       optional minimumfield width, an optionalprecision and an       optionallength modifier.       The overall syntax of a conversion specification is:           %[argument$][flags][width][.precision][length modifier]conversion       The arguments must correspond properly (after type promotion) with       the conversion specifier.  By default, the arguments are used in       the order given, where each '*' (seeField width andPrecision       below) and each conversion specifier asks for the next argument       (and it is an error if insufficiently many arguments are given).       One can also specify explicitly which argument is taken, at each       place where an argument is required, by writing "%m$" instead of       '%' and "*m$" instead of '*', where the decimal integerm denotes       the position in the argument list of the desired argument, indexed       starting from 1.  Thus,           printf("%*d", width, num);       and           printf("%2$*1$d", width, num);       are equivalent.  The second style allows repeated references to       the same argument.  The C99 standard does not include the style       using '$', which comes from the Single UNIX Specification.  If the       style using '$' is used, it must be used throughout for all       conversions taking an argument and all width and precision       arguments, but it may be mixed with "%%" formats, which do not       consume an argument.  There may be no gaps in the numbers of       arguments specified using '$'; for example, if arguments 1 and 3       are specified, argument 2 must also be specified somewhere in the       format string.       For some numeric conversions a radix character ("decimal point")       or thousands' grouping character is used.  The actual character       used depends on theLC_NUMERICpart of the locale.  (Seesetlocale(3).)  The POSIX locale uses '.' as radix character, and       does not have a grouping character.  Thus,           printf("%'.2f", 1234567.89);       results in "1234567.89" in the POSIX locale, in "1234567,89" in       the nl_NL locale, and in "1.234.567,89" in the da_DK locale.Flag characters       The character % is followed by zero or more of the following       flags:#The value should be converted to an "alternate form".  Foroconversions, the first character of the output string is              made zero (by prefixing a 0 if it was not zero already).              ForxandXconversions, a nonzero result has the string              "0x" (or "0X" forXconversions) prepended to it.  Fora,A,e,E,f,F,g, andGconversions, the result will always              contain a decimal point, even if no digits follow it              (normally, a decimal point appears in the results of those              conversions only if a digit follows).  ForgandG              conversions, trailing zeros are not removed from the result              as they would otherwise be.  Form, iferrno contains a              valid error code, the output ofstrerrorname_np(errno) is              printed; otherwise, the value stored inerrno is printed as              a decimal number.  For other conversions, the result is              undefined.0The value should be zero padded.  Ford,i,o,u,x,X,a,A,e,E,f,F,g, andGconversions, the converted value is              padded on the left with zeros rather than blanks.  If the0              and-flags both appear, the0flag is ignored.  If a              precision is given with an integer conversion (d,i,o,u,x, andX), the0flag is ignored.  For other conversions,              the behavior is undefined.-The converted value is to be left adjusted on the field              boundary.  (The default is right justification.)  The              converted value is padded on the right with blanks, rather              than on the left with blanks or zeros.  A-overrides a0              if both are given.' '(a space) A blank should be left before a positive number              (or empty string) produced by a signed conversion.+A sign (+ or -) should always be placed before a number              produced by a signed conversion.  By default, a sign is              used only for negative numbers.  A+overrides a space if              both are used.       The five flag characters above are defined in the C99 standard.       POSIX specifies one further flag character.'For decimal conversion (i,d,u,f,F,g,G) the output is              to be grouped with thousands' grouping characters as anon-monetary quantity.  Misleadingly, this isn't necessarily              every thousand: for example Karbi ("mjw_IN"), groups its              digits into 3 once, then 2 repeatedly.  Comparelocale(7)grouping andthousands_sep, contrast withmon_grouping/mon_thousands_sep andstrfmon(3).  This is a              no-op in the default "C" locale.       glibc 2.2 adds one further flag character.IFor decimal integer conversion (i,d,u) the output uses              the locale's alternative output digits, if any.  For              example, since glibc 2.2.3 this will give Arabic-Indic              digits in the Persian ("fa_IR") locale.Field width       An optional decimal digit string (with nonzero first digit)       specifying a minimum field width.  If the converted value has       fewer characters than the field width, it will be padded with       spaces on the left (or right, if the left-adjustment flag has been       given).  Instead of a decimal digit string one may write "*" or       "*m$" (for some decimal integerm) to specify that the field width       is given in the next argument, or in them-th argument,       respectively, which must be of typeint.  A negative field width       is taken as a '-' flag followed by a positive field width.  In no       case does a nonexistent or small field width cause truncation of a       field; if the result of a conversion is wider than the field       width, the field is expanded to contain the conversion result.Precision       An optional precision, in the form of a period ('.')  followed by       an optional decimal digit string.  Instead of a decimal digit       string one may write "*" or "*m$" (for some decimal integerm) to       specify that the precision is given in the next argument, or in       them-th argument, respectively, which must be of typeint.  If       the precision is given as just '.', the precision is taken to be       zero.  A negative precision is taken as if the precision were       omitted.  This gives the minimum number of digits to appear ford,i,o,u,x, andXconversions, the number of digits to appear       after the radix character fora,A,e,E,f, andFconversions,       the maximum number of significant digits forgandGconversions,       or the maximum number of characters to be printed from a string       forsandSconversions.Length modifier       Here, "integer conversion" stands ford,i,o,u,x, orX       conversion.hhA following integer conversion corresponds to asigned char              orunsigned char argument, or a followingnconversion              corresponds to a pointer to asigned char argument.hA following integer conversion corresponds to ashort orunsigned short argument, or a followingnconversion              corresponds to a pointer to ashort argument.l(ell) A following integer conversion corresponds to along              orunsigned long argument, or a followingnconversion              corresponds to a pointer to along argument, or a followingcconversion corresponds to awint_t argument, or a              followingsconversion corresponds to a pointer towchar_t              argument.  On a followinga,A,e,E,f,F,g, orG              conversion, this length modifier is ignored (C99; not in              SUSv2).ll(ell-ell).  A following integer conversion corresponds to along long orunsigned long long argument, or a followingn              conversion corresponds to a pointer to along long              argument.qA synonym forll.  This is a nonstandard extension, derived              from BSD; avoid its use in new code.LA followinga,A,e,E,f,F,g, orGconversion              corresponds to along double argument.  (C99 allows %LF,              but SUSv2 does not.)jA following integer conversion corresponds to anintmax_t              oruintmax_t argument, or a followingnconversion              corresponds to a pointer to anintmax_t argument.zA following integer conversion corresponds to asize_t orssize_t argument, or a followingnconversion corresponds              to a pointer to asize_t argument.ZA nonstandard synonym forzthat predates the appearance ofz.  Do not use in new code.tA following integer conversion corresponds to aptrdiff_t              argument, or a followingnconversion corresponds to a              pointer to aptrdiff_t argument.       SUSv3 specifies all of the above, except for those modifiers       explicitly noted as being nonstandard extensions.  SUSv2 specified       only the length modifiersh(inhd,hi,ho,hx,hX,hn) andl(inld,li,lo,lx,lX,ln,lc,ls) andL(inLe,LE,Lf,Lg,LG).       As a nonstandard extension, the GNU implementations treatsllandLas synonyms, so that one can, for example, writellg(as a       synonym for the standards-compliantLg) andLd(as a synonym for       the standards compliantlld).  Such usage is nonportable.Conversion specifiers       A character that specifies the type of conversion to be applied.       The conversion specifiers and their meanings are:d,iTheint argument is converted to signed decimal notation.              The precision, if any, gives the minimum number of digits              that must appear; if the converted value requires fewer              digits, it is padded on the left with zeros.  The default              precision is 1.  When 0 is printed with an explicit              precision 0, the output is empty.o,u,x,X              Theunsigned int argument is converted to unsigned octal              (o), unsigned decimal (u), or unsigned hexadecimal (xandX) notation.  The lettersabcdefare used forx              conversions; the lettersABCDEFare used forXconversions.              The precision, if any, gives the minimum number of digits              that must appear; if the converted value requires fewer              digits, it is padded on the left with zeros.  The default              precision is 1.  When 0 is printed with an explicit              precision 0, the output is empty.e,EThedouble argument is rounded and converted in the style              [-]d.ddde±dd where there is one digit (which is nonzero if              the argument is nonzero) before the decimal-point character              and the number of digits after it is equal to the              precision; if the precision is missing, it is taken as 6;              if the precision is zero, no decimal-point character              appears.  AnEconversion uses the letterE(rather thane)              to introduce the exponent.  The exponent always contains at              least two digits; if the value is zero, the exponent is 00.f,FThedouble argument is rounded and converted to decimal              notation in the style [-]ddd.ddd, where the number of              digits after the decimal-point character is equal to the              precision specification.  If the precision is missing, it              is taken as 6; if the precision is explicitly zero, no              decimal-point character appears.  If a decimal point              appears, at least one digit appears before it.              (SUSv2 does not know aboutFand says that character string              representations for infinity and NaN may be made available.              SUSv3 adds a specification forF.  The C99 standard              specifies "[-]inf" or "[-]infinity" for infinity, and a              string starting with "nan" for NaN, in the case off              conversion, and "[-]INF" or "[-]INFINITY" or "NAN" in the              case ofFconversion.)g,GThedouble argument is converted in stylefore(orForE              forGconversions).  The precision specifies the number of              significant digits.  If the precision is missing, 6 digits              are given; if the precision is zero, it is treated as 1.              Styleeis used if the exponent from its conversion is less              than -4 or greater than or equal to the precision.              Trailing zeros are removed from the fractional part of the              result; a decimal point appears only if it is followed by              at least one digit.a,A(C99; not in SUSv2, but added in SUSv3) Foraconversion,              thedouble argument is converted to hexadecimal notation              (using the letters abcdef) in the style [-]0xh.hhhhp±d; forAconversion the prefix0X, the letters ABCDEF, and the              exponent separatorPis used.  There is one hexadecimal              digit before the radix point, and the number of digits              after it is equal to the precision.  The default precision              suffices for an exact representation of the value if an              exact representation in base 2 exists and otherwise is              sufficiently large to distinguish values of typedouble.              The digit before the radix point is unspecified for              nonnormalized numbers, and nonzero but otherwise              unspecified for normalized numbers.  The exponent,d, is              the appropriate exponent of 2 expressed as a decimal              integer; it always contains at least one digit; if the              value is zero, the exponent is 0.cIf nolmodifier is present, theint argument is converted              to anunsigned char, and the resulting character is              written.  If anlmodifier is present, thewint_t (wide              character) argument is converted to a multibyte sequence by              a call to thewcrtomb(3) function, with a conversion state              starting in the initial state, and the resulting multibyte              string is written.sIf nolmodifier is present: theconst char * argument is              expected to be a pointer to an array of character type              (pointer to a string).  Characters from the array are              written up to (but not including) a terminating null byte              ('\0'); if a precision is specified, no more than the              number specified are written.  If a precision is given, no              null byte need be present; if the precision is not              specified, or is greater than the size of the array, the              array must contain a terminating null byte.              If anlmodifier is present: theconst wchar_t * argument              is expected to be a pointer to an array of wide characters.              Wide characters from the array are converted to multibyte              characters (each by a call to thewcrtomb(3) function, with              a conversion state starting in the initial state before the              first wide character), up to and including a terminating              null wide character.  The resulting multibyte characters              are written up to (but not including) the terminating null              byte.  If a precision is specified, no more bytes than the              number specified are written, but no partial multibyte              characters are written.  Note that the precision determines              the number ofbytes written, not the number ofwidecharacters orscreen positions.  The array must contain a              terminating null wide character, unless a precision is              given and it is so small that the number of bytes written              exceeds it before the end of the array is reached.C(Not in C99 or C11, but in SUSv2, SUSv3, and SUSv4.)              Synonym forlc.  Don't use.S(Not in C99 or C11, but in SUSv2, SUSv3, and SUSv4.)              Synonym forls.  Don't use.pThevoid * pointer argument is printed in hexadecimal (as              if by%#xor%#lx).nThe number of characters written so far is stored into the              integer pointed to by the corresponding argument.  That              argument shall be anint *, or variant whose size matches              the (optionally) supplied integer length modifier.  No              argument is converted.  (This specifier is not supported by              the bionic C library.)  The behavior is undefined if the              conversion specification includes any flags, a field width,              or a precision.m(glibc extension; supported by uClibc and musl, and on              Android from API level 29.)  Print output ofstrerror(errno) (orstrerrorname_np(errno) in the alternate              form).  No argument is required.%A '%' is written.  No argument is converted.  The complete              conversion specification is '%%'.

RETURN VALUE        top

       Upon successful return, these functions return the number of bytes       printed (excluding the null byte used to end output to strings).       The functionssnprintf() andvsnprintf() do not write more thansize bytes (including the terminating null byte ('\0')).  If the       output was truncated due to this limit, then the return value is       the number of characters (excluding the terminating null byte)       which would have been written to the final string if enough space       had been available.  Thus, a return value ofsize or more means       that the output was truncated.  (See also below under CAVEATS.)       On error, a negative value is returned, anderrno is set to       indicate the error.

ERRORS        top

       Seewrite(2) andputwc(3).  In addition, the following error may       occur:EOVERFLOW              The value to be returned is greater thanINT_MAX.       Thedprintf() function may fail additionally if:EBADFThefd argument is not a valid file descriptor.

ATTRIBUTES        top

       For an explanation of the terms used in this section, seeattributes(7).       ┌───────────────────────────────┬───────────────┬────────────────┐       │InterfaceAttributeValue│       ├───────────────────────────────┼───────────────┼────────────────┤       │printf(),fprintf(),          │ Thread safety │ MT-Safe locale │       │sprintf(),snprintf(),        │               │                │       │vprintf(),vfprintf(),        │               │                │       │vsprintf(),vsnprintf()       │               │                │       └───────────────────────────────┴───────────────┴────────────────┘

STANDARDS        top

fprintf()printf()sprintf()vprintf()vfprintf()vsprintf()snprintf()vsnprintf()              C11, POSIX.1-2008.dprintf()vdprintf()              GNU, POSIX.1-2008.

HISTORY        top

fprintf()printf()sprintf()vprintf()vfprintf()vsprintf()              C89, POSIX.1-2001.snprintf()vsnprintf()              SUSv2, C99, POSIX.1-2001.              Concerning the return value ofsnprintf(), SUSv2 and C99              contradict each other: whensnprintf() is called withsize=0 then SUSv2 stipulates an unspecified return value              less than 1, while C99 allowsstr to be NULL in this case,              and gives the return value (as always) as the number of              characters that would have been written in case the output              string has been large enough.  POSIX.1-2001 and later align              their specification ofsnprintf() with C99.dprintf()vdprintf()              GNU, POSIX.1-2008.       Issue 4 of the X/Open Portability Guide (SUSv1, 1994) adds'.       glibc 2.1 adds length modifiershh,j,t, andzand conversion       charactersaandA.       glibc 2.2 adds the conversion characterFwith C99 semantics, and       the flag characterI.       glibc 2.35 gives a meaning to the alternate form (#) of them       conversion specifier, that is%#m.

CAVEATS        top

       Some programs imprudently rely on code such as the following           sprintf(buf, "%s some further text", buf);       to append text tobuf.  However, the standards explicitly note       that the results are undefined if source and destination buffers       overlap when callingsprintf(),snprintf(),vsprintf(), andvsnprintf().  Depending on the version ofgcc(1) used, and the       compiler options employed, calls such as the above willnot       produce the expected results.       The glibc implementation of the functionssnprintf() andvsnprintf() conforms to the C99 standard, that is, behaves as       described above, since glibc 2.1.  Until glibc 2.0.6, they would       return -1 when the output was truncated.

BUGS        top

       Becausesprintf() andvsprintf() assume an arbitrarily long       string, callers must be careful not to overflow the actual space;       this is often impossible to assure.  Note that the length of the       strings produced is locale-dependent and difficult to predict.       Usesnprintf() andvsnprintf() instead (orasprintf(3) andvasprintf(3)).       Code such asprintf(foo);often indicates a bug, sincefoo may       contain a % character.  Iffoo comes from untrusted user input, it       may contain%n, causing theprintf() call to write to memory and       creating a security hole.

EXAMPLES        top

       To printPi to five decimal places:           #include <math.h>           #include <stdio.h>           fprintf(stdout, "pi = %.5f\n", 4 * atan(1.0));       To print a date and time in the form "Sunday, July 3, 10:02",       whereweekday andmonth are pointers to strings:           #include <stdio.h>           fprintf(stdout, "%s, %s %d, %.2d:%.2d\n",                   weekday, month, day, hour, min);       Many countries use the day-month-year order.  Hence, an       internationalized version must be able to print the arguments in       an order specified by the format:           #include <stdio.h>           fprintf(stdout, format,                   weekday, month, day, hour, min);       whereformat depends on locale, and may permute the arguments.       With the value:           "%1$s, %3$d. %2$s, %4$d:%5$.2d\n"       one might obtain "Sonntag, 3. Juli, 10:02".       To allocate a sufficiently large string and print into it (code       correct for both glibc 2.0 and glibc 2.1):       #include <stdio.h>       #include <stdlib.h>       #include <stdarg.h>       char *       make_message(const char *fmt, ...)       {           int n = 0;           size_t size = 0;           char *p = NULL;           va_list ap;           /* Determine required size. */           va_start(ap, fmt);           n = vsnprintf(p, size, fmt, ap);           va_end(ap);           if (n < 0)               return NULL;           size = (size_t) n + 1;      /* One extra byte for '\0' */           p = malloc(size);           if (p == NULL)               return NULL;           va_start(ap, fmt);           n = vsnprintf(p, size, fmt, ap);           va_end(ap);           if (n < 0) {               free(p);               return NULL;           }           return p;       }       If truncation occurs in glibc versions prior to glibc 2.0.6, this       is treated as an error instead of being handled gracefully.

SEE ALSO        top

printf(1),asprintf(3),puts(3),scanf(3),setlocale(3),strfromd(3),wcrtomb(3),wprintf(3),locale(5)

COLOPHON        top

       This page is part of theman-pages (Linux kernel and C library       user-space interface documentation) project.  Information about       the project can be found at        ⟨https://www.kernel.org/doc/man-pages/⟩.  If you have a bug report       for this manual page, see       ⟨https://git.kernel.org/pub/scm/docs/man-pages/man-pages.git/tree/CONTRIBUTING⟩.       This page was obtained from the tarball man-pages-6.15.tar.gz       fetched from       ⟨https://mirrors.edge.kernel.org/pub/linux/docs/man-pages/⟩ on       2025-08-11.  If you discover any rendering problems in this HTML       version of the page, or you believe there is a better or more up-       to-date source for the page, or you have corrections or       improvements to the information in this COLOPHON (which isnot       part of the original manual page), send a mail to       man-pages@man7.orgLinux man-pages 6.15            2025-07-19printf(3)

Pages that refer to this page:bash(1)find(1)gawk(1)hexdump(1)printf(1)ps(1)time(1)perf_event_open(2)asprintf(3)avc_init(3)curs_printw(3x)curs_termcap(3x)ecvt(3)ecvt_r(3)err(3)errno(3)error(3)FILE(3type)form_field_validation(3x)fwide(3)gcvt(3)intmax_t(3type)intN_t(3type)intptr_t(3type)lber-encode(3)localeconv(3)lttng-ust(3)lttng_ust_tracef(3)lttng_ust_tracelog(3)numa(3)pmnotifyerr(3)pmnumberstr(3)pmprintf(3)pmsprintf(3)printf.h(3head)ptrdiff_t(3type)qecvt(3)rpc(3)scanf(3)sd_bus_error(3)sd_bus_message_new_method_error(3)sd-daemon(3)sd-id128(3)sd_id128_to_string(3)sd_journal_print(3)sd_journal_stream_fd(3)selinux_set_callback(3)setbuf(3)size_t(3type)sscanf(3)stdarg(3)stdin(3)stdio(3)strfmon(3)strfromd(3)strftime(3)syslog(3)uuid_parse(3)void(3type)wprintf(3)slapd.conf(5)slapd-config(5)terminfo(5)feature_test_macros(7)locale(7)signal-safety(7)system_data_types(7)btrfstune(8)rpm(8)slappasswd(8)



HTML rendering created 2025-09-06 byMichael Kerrisk, author ofThe Linux Programming Interface.

For details of in-depthLinux/UNIX system programming training courses that I teach, lookhere.

Hosting byjambit GmbH.

Cover of TLPI


[8]ページ先頭

©2009-2025 Movatter.jp