📄 stdio.texi
字号:
@node I/O on Streams, Low-Level I/O, I/O Overview, Top@chapter Input/Output on StreamsThis chapter describes the functions for creating streams and performinginput and output operations on them. As discussed in @ref{I/OOverview}, a stream is a fairly abstract, high-level conceptrepresenting a communications channel to a file, device, or process.@menu* Streams:: About the data type representing a stream.* Standard Streams:: Streams to the standard input and output devices are created for you.* Opening Streams:: How to create a stream to talk to a file.* Closing Streams:: Close a stream when you are finished with it.* Simple Output:: Unformatted output by characters and lines.* Character Input:: Unformatted input by characters and words.* Line Input:: Reading a line or a record from a stream.* Unreading:: Peeking ahead/pushing back input just read.* Formatted Output:: @code{printf} and related functions.* Customizing Printf:: You can define new conversion specifiers for @code{printf} and friends.* Formatted Input:: @code{scanf} and related functions.* Block Input/Output:: Input and output operations on blocks of data.* EOF and Errors:: How you can tell if an I/O error happens.* Binary Streams:: Some systems distinguish between text files and binary files.* File Positioning:: About random-access streams.* Portable Positioning:: Random access on peculiar ANSI C systems.* Stream Buffering:: How to control buffering of streams.* Other Kinds of Streams:: Streams that do not necessarily correspond to an open file. @end menu@node Streams@section StreamsFor historical reasons, the type of the C data structure that representsa stream is called @code{FILE} rather than ``stream''. Since most ofthe library functions deal with objects of type @code{FILE *}, sometimesthe term @dfn{file pointer} is also used to mean ``stream''. This leadsto unfortunate confusion over terminology in many books on C. Thismanual, however, is careful to use the terms ``file'' and ``stream''only in the technical sense.@cindex file pointer@pindex stdio.hThe @code{FILE} type is declared in the header file @file{stdio.h}.@comment stdio.h@comment ANSI@deftp {Data Type} FILEThis is the data type used to represent stream objects. A @code{FILE}object holds all of the internal state information about the connectionto the associated file, including such things as the file positionindicator and buffering information. Each stream also has error andend-of-file status indicators that can be tested with the @code{ferror}and @code{feof} functions; see @ref{EOF and Errors}.@end deftp@code{FILE} objects are allocated and managed internally by theinput/output library functions. Don't try to create your own objects oftype @code{FILE}; let the library do it. Your programs shoulddeal only with pointers to these objects (that is, @code{FILE *} values)rather than the objects themselves.@c !!! should say that FILE's have "No user-servicable parts inside."@node Standard Streams@section Standard Streams@cindex standard streams@cindex streams, standardWhen the @code{main} function of your program is invoked, it already hasthree predefined streams open and available for use. These representthe ``standard'' input and output channels that have been establishedfor the process.These streams are declared in the header file @file{stdio.h}.@pindex stdio.h@comment stdio.h@comment ANSI@deftypevar {FILE *} stdinThe @dfn{standard input} stream, which is the normal source of input for theprogram.@end deftypevar@cindex standard input stream@comment stdio.h@comment ANSI@deftypevar {FILE *} stdoutThe @dfn{standard output} stream, which is used for normal output fromthe program.@end deftypevar@cindex standard output stream@comment stdio.h@comment ANSI@deftypevar {FILE *} stderrThe @dfn{standard error} stream, which is used for error messages anddiagnostics issued by the program.@end deftypevar@cindex standard error streamIn the GNU system, you can specify what files or processes correspond tothese streams using the pipe and redirection facilities provided by theshell. (The primitives shells use to implement these facilities aredescribed in @ref{File System Interface}.) Most other operating systemsprovide similar mechanisms, but the details of how to use them can vary.In the GNU C library, @code{stdin}, @code{stdout}, and @code{stderr} arenormal variables which you can set just like any others. For example, to redirectthe standard output to a file, you could do:@smallexamplefclose (stdout);stdout = fopen ("standard-output-file", "w");@end smallexampleNote however, that in other systems @code{stdin}, @code{stdout}, and@code{stderr} are macros that you cannot assign to in the normal way.But you can use @code{freopen} to get the effect of closing one andreopening it. @xref{Opening Streams}.@node Opening Streams@section Opening Streams@cindex opening a streamOpening a file with the @code{fopen} function creates a new stream andestablishes a connection between the stream and a file. This mayinvolve creating a new file. @pindex stdio.hEverything described in this section is declared in the header file@file{stdio.h}.@comment stdio.h@comment ANSI@deftypefun {FILE *} fopen (const char *@var{filename}, const char *@var{opentype})The @code{fopen} function opens a stream for I/O to the file@var{filename}, and returns a pointer to the stream.The @var{opentype} argument is a string that controls how the file isopened and specifies attributes of the resulting stream. It must beginwith one of the following sequences of characters:@table @samp@item rOpen an existing file for reading only.@item wOpen the file for writing only. If the file already exists, it istruncated to zero length. Otherwise a new file is created.@item aOpen a file for append access; that is, writing at the end of file only.If the file already exists, its initial contents are unchanged andoutput to the stream is appended to the end of the file.Otherwise, a new, empty file is created.@item r+Open an existing file for both reading and writing. The initial contentsof the file are unchanged and the initial file position is at thebeginning of the file.@item w+Open a file for both reading and writing. If the file already exists, itis truncated to zero length. Otherwise, a new file is created.@item a+Open or create file for both reading and appending. If the file exists,its initial contents are unchanged. Otherwise, a new file is created.The initial file position for reading is at the beginning of the file,but output is always appended to the end of the file.@end tableAs you can see, @samp{+} requests a stream that can do both input andoutput. The ANSI standard says that when using such a stream, you mustcall @code{fflush} (@pxref{Stream Buffering}) or a file positioningfunction such as @code{fseek} (@pxref{File Positioning}) when switchingfrom reading to writing or vice versa. Otherwise, internal buffersmight not be emptied properly. The GNU C library does not have thislimitation; you can do arbitrary reading and writing operations on astream in whatever order.The GNU C library defines one additional character for use in@var{opentype}: the character @samp{x} insists on creating a newfile---if a file @var{filename} already exists, @code{fopen} failsrather than opening it. If you use @samp{x} you can are guaranteed thatyou will not clobber an existing file. This is equivalent to the@code{O_EXCL} option to the @code{open} function (@pxref{Opening andClosing Files}).The character @samp{b} in @var{opentype} has a standard meaning; itrequests a binary stream rather than a text stream. But this makes nodifference in POSIX systems (including the GNU system). If both@samp{+} and @samp{b} are specified, they can appear in either order.@xref{Binary Streams}.Any other characters in @var{opentype} are simply ignored. They may bemeaningful in other systems.If the open fails, @code{fopen} returns a null pointer.@end deftypefunYou can have multiple streams (or file descriptors) pointing to the samefile open at the same time. If you do only input, this worksstraightforwardly, but you must be careful if any output streams areincluded. @xref{Stream/Descriptor Precautions}. This is equally truewhether the streams are in one program (not usual) or in severalprograms (which can easily happen). It may be advantageous to use thefile locking facilities to avoid simultaneous access. @xref{FileLocks}.@comment stdio.h@comment ANSI@deftypevr Macro int FOPEN_MAXThe value of this macro is an integer constant expression thatrepresents the minimum number of streams that the implementationguarantees can be open simultaneously. You might be able to open morethan this many streams, but that is not guaranteed. The value of thisconstant is at least eight, which includes the three standard streams@code{stdin}, @code{stdout}, and @code{stderr}. In POSIX.1 systems thisvalue is determined by the @code{OPEN_MAX} parameter; @pxref{GeneralLimits}. In BSD and GNU, it is controlled by the @code{RLIMIT_NOFILE}resource limit; @pxref{Limits on Resources}.@end deftypevr@comment stdio.h@comment ANSI@deftypefun {FILE *} freopen (const char *@var{filename}, const char *@var{opentype}, FILE *@var{stream})This function is like a combination of @code{fclose} and @code{fopen}.It first closes the stream referred to by @var{stream}, ignoring anyerrors that are detected in the process. (Because errors are ignored,you should not use @code{freopen} on an output stream if you haveactually done any output using the stream.) Then the file named by@var{filename} is opened with mode @var{opentype} as for @code{fopen},and associated with the same stream object @var{stream}.If the operation fails, a null pointer is returned; otherwise,@code{freopen} returns @var{stream}.@code{freopen} has traditionally been used to connect a standard streamsuch as @code{stdin} with a file of your own choice. This is useful inprograms in which use of a standard stream for certain purposes ishard-coded. In the GNU C library, you can simply close the standardstreams and open new ones with @code{fopen}. But other systems lackthis ability, so using @code{freopen} is more portable.@end deftypefun@node Closing Streams@section Closing Streams@cindex closing a streamWhen a stream is closed with @code{fclose}, the connection between thestream and the file is cancelled. After you have closed a stream, youcannot perform any additional operations on it.@comment stdio.h@comment ANSI@deftypefun int fclose (FILE *@var{stream})This function causes @var{stream} to be closed and the connection tothe corresponding file to be broken. Any buffered output is writtenand any buffered input is discarded. The @code{fclose} function returnsa value of @code{0} if the file was closed successfully, and @code{EOF}if an error was detected. It is important to check for errors when you call @code{fclose} to closean output stream, because real, everyday errors can be detected at thistime. For example, when @code{fclose} writes the remaining bufferedoutput, it might get an error because the disk is full. Even if youknow the buffer is empty, errors can still occur when closing a file ifyou are using NFS.The function @code{fclose} is declared in @file{stdio.h}.@end deftypefunIf the @code{main} function to your program returns, or if you call the@code{exit} function (@pxref{Normal Termination}), all open streams areautomatically closed properly. If your program terminates in any othermanner, such as by calling the @code{abort} function (@pxref{Aborting aProgram}) or from a fatal signal (@pxref{Signal Handling}), open streamsmight not be closed properly. Buffered output might not be flushed andfiles may be incomplete. For more information on buffering of streams,see @ref{Stream Buffering}.@node Simple Output@section Simple Output by Characters or Lines@cindex writing to a stream, by charactersThis section describes functions for performing character- andline-oriented output.These functions are declared in the header file @file{stdio.h}.@pindex stdio.h@comment stdio.h@comment ANSI@deftypefun int fputc (int @var{c}, FILE *@var{stream})The @code{fputc} function converts the character @var{c} to type@code{unsigned char}, and writes it to the stream @var{stream}. @code{EOF} is returned if a write error occurs; otherwise thecharacter @var{c} is returned.@end deftypefun@comment stdio.h@comment ANSI@deftypefun int putc (int @var{c}, FILE *@var{stream})This is just like @code{fputc}, except that most systems implement it asa macro, making it faster. One consequence is that it may evaluate the@var{stream} argument more than once. @code{putc} is usually the bestfunction to use for writing a single character.@end deftypefun@comment stdio.h@comment ANSI@deftypefun int putchar (int @var{c})The @code{putchar} function is equivalent to @code{putc} with@code{stdout} as the value of the @var{stream} argument.@end deftypefun@comment stdio.h@comment ANSI@deftypefun int fputs (const char *@var{s}, FILE *@var{stream})The function @code{fputs} writes the string @var{s} to the stream@var{stream}. The terminating null character is not written.This function does @emph{not} add a newline character, either.It outputs only the chars in the string.This function returns @code{EOF} if a write error occurs, and otherwisea non-negative value.For example:@smallexamplefputs ("Are ", stdout);fputs ("you ", stdout);fputs ("hungry?\n", stdout);@end smallexample@noindentoutputs the text @samp{Are you hungry?} followed by a newline.@end deftypefun
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -