📄 stdio.texi
字号:
@node Formatted Output@section Formatted Output@cindex format string, for @code{printf}@cindex template, for @code{printf}@cindex formatted output to a stream@cindex writing to a stream, formattedThe functions described in this section (@code{printf} and relatedfunctions) provide a convenient way to perform formatted output. Youcall @code{printf} with a @dfn{format string} or @dfn{template string}that specifies how to format the values of the remaining arguments.Unless your program is a filter that specifically performs line- orcharacter-oriented processing, using @code{printf} or one of the otherrelated functions described in this section is usually the easiest andmost concise way to perform output. These functions are especiallyuseful for printing error messages, tables of data, and the like.@menu* Formatted Output Basics:: Some examples to get you started.* Output Conversion Syntax:: General syntax of conversion specifications.* Table of Output Conversions:: Summary of output conversions and what they do.* Integer Conversions:: Details about formatting of integers.* Floating-Point Conversions:: Details about formatting of floating-point numbers.* Other Output Conversions:: Details about formatting of strings, characters, pointers, and the like.* Formatted Output Functions:: Descriptions of the actual functions.* Dynamic Output:: Functions that allocate memory for the output.* Variable Arguments Output:: @code{vprintf} and friends.* Parsing a Template String:: What kinds of args does a given template call for? * Example of Parsing:: Sample program using @code{parse_printf_format}.@end menu@node Formatted Output Basics@subsection Formatted Output BasicsThe @code{printf} function can be used to print any number of arguments.The template string argument you supply in a call providesinformation not only about the number of additional arguments, but alsoabout their types and what style should be used for printing them.Ordinary characters in the template string are simply written to theoutput stream as-is, while @dfn{conversion specifications} introduced bya @samp{%} character in the template cause subsequent arguments to beformatted and written to the output stream. For example,@cindex conversion specifications (@code{printf})@smallexampleint pct = 37;char filename[] = "foo.txt";printf ("Processing of `%s' is %d%% finished.\nPlease be patient.\n", filename, pct);@end smallexample@noindentproduces output like@smallexampleProcessing of `foo.txt' is 37% finished.Please be patient.@end smallexampleThis example shows the use of the @samp{%d} conversion to specify thatan @code{int} argument should be printed in decimal notation, the@samp{%s} conversion to specify printing of a string argument, andthe @samp{%%} conversion to print a literal @samp{%} character.There are also conversions for printing an integer argument as anunsigned value in octal, decimal, or hexadecimal radix (@samp{%o},@samp{%u}, or @samp{%x}, respectively); or as a character value(@samp{%c}).Floating-point numbers can be printed in normal, fixed-point notationusing the @samp{%f} conversion or in exponential notation using the@samp{%e} conversion. The @samp{%g} conversion uses either @samp{%e}or @samp{%f} format, depending on what is more appropriate for themagnitude of the particular number.You can control formatting more precisely by writing @dfn{modifiers}between the @samp{%} and the character that indicates which conversionto apply. These slightly alter the ordinary behavior of the conversion.For example, most conversion specifications permit you to specify aminimum field width and a flag indicating whether you want the resultleft- or right-justified within the field.The specific flags and modifiers that are permitted and theirinterpretation vary depending on the particular conversion. They're alldescribed in more detail in the following sections. Don't worry if thisall seems excessively complicated at first; you can almost always getreasonable free-format output without using any of the modifiers at all.The modifiers are mostly used to make the output look ``prettier'' intables.@node Output Conversion Syntax@subsection Output Conversion SyntaxThis section provides details about the precise syntax of conversionspecifications that can appear in a @code{printf} templatestring.Characters in the template string that are not part of aconversion specification are printed as-is to the output stream.Multibyte character sequences (@pxref{Extended Characters}) are permitted ina template string.The conversion specifications in a @code{printf} template string havethe general form:@example% @var{flags} @var{width} @r{[} . @var{precision} @r{]} @var{type} @var{conversion}@end exampleFor example, in the conversion specifier @samp{%-10.8ld}, the @samp{-}is a flag, @samp{10} specifies the field width, the precision is@samp{8}, the letter @samp{l} is a type modifier, and @samp{d} specifiesthe conversion style. (This particular type specifier says toprint a @code{long int} argument in decimal notation, with a minimum of8 digits left-justified in a field at least 10 characters wide.)In more detail, output conversion specifications consist of aninitial @samp{%} character followed in sequence by:@itemize @bullet@item Zero or more @dfn{flag characters} that modify the normal behavior ofthe conversion specification.@cindex flag character (@code{printf})@item An optional decimal integer specifying the @dfn{minimum field width}.If the normal conversion produces fewer characters than this, the fieldis padded with spaces to the specified width. This is a @emph{minimum}value; if the normal conversion produces more characters than this, thefield is @emph{not} truncated. Normally, the output is right-justifiedwithin the field.@cindex minimum field width (@code{printf})You can also specify a field width of @samp{*}. This means that thenext argument in the argument list (before the actual value to beprinted) is used as the field width. The value must be an @code{int}.If the value is negative, this means to set the @samp{-} flag (seebelow) and to use the absolute value as the field width.@item An optional @dfn{precision} to specify the number of digits to bewritten for the numeric conversions. If the precision is specified, itconsists of a period (@samp{.}) followed optionally by a decimal integer(which defaults to zero if omitted).@cindex precision (@code{printf})You can also specify a precision of @samp{*}. This means that the nextargument in the argument list (before the actual value to be printed) isused as the precision. The value must be an @code{int}, and is ignoredif it is negative. If you specify @samp{*} for both the field width andprecision, the field width argument precedes the precision argument.Other C library versions may not recognize this syntax.@itemAn optional @dfn{type modifier character}, which is used to specify thedata type of the corresponding argument if it differs from the defaulttype. (For example, the integer conversions assume a type of @code{int},but you can specify @samp{h}, @samp{l}, or @samp{L} for other integertypes.)@cindex type modifier character (@code{printf})@itemA character that specifies the conversion to be applied.@end itemizeThe exact options that are permitted and how they are interpreted vary between the different conversion specifiers. See the descriptions of theindividual conversions for information about the particular options thatthey use.With the @samp{-Wformat} option, the GNU C compiler checks calls to@code{printf} and related functions. It examines the format string andverifies that the correct number and types of arguments are supplied.There is also a GNU C syntax to tell the compiler that a function youwrite uses a @code{printf}-style format string. @xref{Function Attributes, , Declaring Attributes of Functions,gcc.info, Using GNU CC}, for more information.@node Table of Output Conversions@subsection Table of Output Conversions@cindex output conversions, for @code{printf}Here is a table summarizing what all the different conversions do:@table @asis@item @samp{%d}, @samp{%i}Print an integer as a signed decimal number. @xref{IntegerConversions}, for details. @samp{%d} and @samp{%i} are synonymous foroutput, but are different when used with @code{scanf} for input(@pxref{Table of Input Conversions}).@item @samp{%o}Print an integer as an unsigned octal number. @xref{IntegerConversions}, for details.@item @samp{%u}Print an integer as an unsigned decimal number. @xref{IntegerConversions}, for details.@item @samp{%x}, @samp{%X}Print an integer as an unsigned hexadecimal number. @samp{%x} useslower-case letters and @samp{%X} uses upper-case. @xref{IntegerConversions}, for details.@item @samp{%f}Print a floating-point number in normal (fixed-point) notation.@xref{Floating-Point Conversions}, for details.@item @samp{%e}, @samp{%E}Print a floating-point number in exponential notation. @samp{%e} useslower-case letters and @samp{%E} uses upper-case. @xref{Floating-PointConversions}, for details.@item @samp{%g}, @samp{%G}Print a floating-point number in either normal or exponential notation,whichever is more appropriate for its magnitude. @samp{%g} useslower-case letters and @samp{%G} uses upper-case. @xref{Floating-PointConversions}, for details.@item @samp{%c}Print a single character. @xref{Other Output Conversions}.@item @samp{%s}Print a string. @xref{Other Output Conversions}.@item @samp{%p}Print the value of a pointer. @xref{Other Output Conversions}.@item @samp{%n}Get the number of characters printed so far. @xref{Other Output Conversions}.Note that this conversion specification never produces any output.@item @samp{%m}Print the string corresponding to the value of @code{errno}.(This is a GNU extension.)@xref{Other Output Conversions}.@item @samp{%%}Print a literal @samp{%} character. @xref{Other Output Conversions}.@end tableIf the syntax of a conversion specification is invalid, unpredictablethings will happen, so don't do this. If there aren't enough functionarguments provided to supply values for all the conversionspecifications in the template string, or if the arguments are not ofthe correct types, the results are unpredictable. If you supply morearguments than conversion specifications, the extra argument values aresimply ignored; this is sometimes useful.@node Integer Conversions@subsection Integer ConversionsThis section describes the options for the @samp{%d}, @samp{%i},@samp{%o}, @samp{%u}, @samp{%x}, and @samp{%X} conversionspecifications. These conversions print integers in various formats.The @samp{%d} and @samp{%i} conversion specifications both print an@code{int} argument as a signed decimal number; while @samp{%o},@samp{%u}, and @samp{%x} print the argument as an unsigned octal,decimal, or hexadecimal number (respectively). The @samp{%X} conversionspecification is just like @samp{%x} except that it uses the characters@samp{ABCDEF} as digits instead of @samp{abcdef}.The following flags are meaningful:@table @asis@item @samp{-}Left-justify the result in the field (instead of the normalright-justification).@item @samp{+}For the signed @samp{%d} and @samp{%i} conversions, print aplus sign if the value is positive.@item @samp{ }For the signed @samp{%d} and @samp{%i} conversions, if the resultdoesn't start with a plus or minus sign, prefix it with a spacecharacter instead. Since the @samp{+} flag ensures that the resultincludes a sign, this flag is ignored if you supply both of them.@item @samp{#}For the @samp{%o} conversion, this forces the leading digit to be@samp{0}, as if by increasing the precision. For @samp{%x} or@samp{%X}, this prefixes a leading @samp{0x} or @samp{0X} (respectively)to the result. This doesn't do anything useful for the @samp{%d},@samp{%i}, or @samp{%u} conversions. Using this flag produces outputwhich can be parsed by the @code{strtoul} function (@pxref{Parsing ofIntegers}) and @code{scanf} with the @samp{%i} conversion(@pxref{Numeric Input Conversions}).@item @samp{0}Pad the field with zeros instead of spaces. The zeros are placed afterany indication of sign or base. This flag is ignored if the @samp{-}flag is also specified, or if a precision is specified.@end tableIf a precision is supplied, it specifies the minimum number of digits toappear; leading zeros are produced if necessary. If you don't specify aprecision, the number is printed with as many digits as it needs. Ifyou convert a value of zero with an explicit precision of zero, then nocharacters at all are produced.Without a type modifier, the corresponding argument is treated as an@code{int} (for the signed conversions @samp{%i} and @samp{%d}) or@code{unsigned int} (for the unsigned conversions @samp{%o}, @samp{%u},@samp{%x}, and @samp{%X}). Recall that since @code{printf} and friendsare variadic, any @code{char} and @code{short} arguments areautomatically converted to @code{int} by the default argumentpromotions. For arguments of other integer types, you can use thesemodifiers:@table @samp@item hSpecifies that the argument is a @code{short int} or @code{unsignedshort int}, as appropriate. A @code{short} argument is converted to an@code{int} or @code{unsigned int} by the default argument promotionsanyway, but the @samp{h} modifier says to convert it back to a@code{short} again.@item lSpecifies that the argument is a @code{long int} or @code{unsigned longint}, as appropriate. Two @samp{l} characters is like the @samp{L}modifier, below.@item L@itemx ll@itemx qSpecifies that the argument is a @code{long long int}. (This type isan extension supported by the GNU C compiler. On systems that don'tsupport extra-long integers, this is the same as @code{long int}.)The @samp{q} modifier is another name for the same thing, which comesfrom 4.4 BSD; a @w{@code{long long int}} is sometimes called a ``quad''@code{int}.@item Z
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -