📄 library_11.html
字号:
<!-- This HTML file has been created by texi2html 1.27 from library.texinfo on 3 March 1994 --><TITLE>The GNU C Library - Input/Output on Streams</TITLE><P>Go to the <A HREF="library_10.html" tppabs="http://www.cs.utah.edu/dept/old/texinfo/glibc-manual-0.02/library_10.html">previous</A>, <A HREF="library_12.html" tppabs="http://www.cs.utah.edu/dept/old/texinfo/glibc-manual-0.02/library_12.html">next</A> section.<P><H1><A NAME="SEC117" HREF="library_toc.html#SEC117" tppabs="http://www.cs.utah.edu/dept/old/texinfo/glibc-manual-0.02/library_toc.html#SEC117">Input/Output on Streams</A></H1><P>This chapter describes the functions for creating streams and performinginput and output operations on them. As discussed in section <A HREF="library_10.html#SEC108" tppabs="http://www.cs.utah.edu/dept/old/texinfo/glibc-manual-0.02/library_10.html#SEC108">Input/Output Overview</A>, a stream is a fairly abstract, high-level conceptrepresenting a communications channel to a file, device, or process.<P><H2><A NAME="SEC118" HREF="library_toc.html#SEC118" tppabs="http://www.cs.utah.edu/dept/old/texinfo/glibc-manual-0.02/library_toc.html#SEC118">Streams</A></H2><P>For historical reasons, the type of the C data structure that representsa stream is called <CODE>FILE</CODE> rather than "stream". Since most ofthe library functions deal with objects of type <CODE>FILE *</CODE>, sometimesthe term <DFN>file pointer</DFN> 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.<A NAME="IDX437"></A><A NAME="IDX438"></A><P>The <CODE>FILE</CODE> type is declared in the header file <TT>`stdio.h'</TT>.<P><A NAME="IDX439"></A><U>Data Type:</U> <B>FILE</B><P>This is the data type is used to represent stream objects. A<CODE>FILE</CODE> object holds all of the internal state information about theconnection to the associated file, including such things as the fileposition indicator and buffering information. Each stream also haserror and end-of-file status indicators that can be tested with the<CODE>ferror</CODE> and <CODE>feof</CODE> functions; see section <A HREF="library_11.html#SEC156" tppabs="http://www.cs.utah.edu/dept/old/texinfo/glibc-manual-0.02/library_11.html#SEC156">End-Of-File and Errors</A>.<P><CODE>FILE</CODE> objects are allocated and managed internally by theinput/output library functions. Don't try to create your own objects oftype <CODE>FILE</CODE>; let the library do it. Your programs shoulddeal only with pointers to these objects (that is, <CODE>FILE *</CODE> values)rather than the objects themselves.<P><A NAME="IDX440"></A><A NAME="IDX441"></A><H2><A NAME="SEC119" HREF="library_toc.html#SEC119" tppabs="http://www.cs.utah.edu/dept/old/texinfo/glibc-manual-0.02/library_toc.html#SEC119">Standard Streams</A></H2><P>When the <CODE>main</CODE> 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.<P>These streams are declared in the header file <TT>`stdio.h'</TT>.<A NAME="IDX442"></A><P><A NAME="IDX443"></A><U>Macro:</U> FILE * <B>stdin</B><P>The <DFN>standard input</DFN> stream, which is the normal source of input for theprogram.<A NAME="IDX444"></A><P><A NAME="IDX445"></A><U>Macro:</U> FILE * <B>stdout</B><P>The <DFN>standard output</DFN> stream, which is used for normal output fromthe program.<A NAME="IDX446"></A><P><A NAME="IDX447"></A><U>Macro:</U> FILE * <B>stderr</B><P>The <DFN>standard error</DFN> stream, which is used for error messages anddiagnostics issued by the program.<A NAME="IDX448"></A><P>In 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 section <A HREF="library_13.html#SEC187" tppabs="http://www.cs.utah.edu/dept/old/texinfo/glibc-manual-0.02/library_13.html#SEC187">File System Interface</A>.) Most other operating systemsprovide similar mechanisms, but the details of how to use them can vary.<P>It is probably not a good idea to close any of the standard streams.But you can use <CODE>freopen</CODE> to get te effect of closing one andreopening it. See section <A HREF="library_11.html#SEC120" tppabs="http://www.cs.utah.edu/dept/old/texinfo/glibc-manual-0.02/library_11.html#SEC120">Opening Streams</A>.<P><H2><A NAME="SEC120" HREF="library_toc.html#SEC120" tppabs="http://www.cs.utah.edu/dept/old/texinfo/glibc-manual-0.02/library_toc.html#SEC120">Opening Streams</A></H2><A NAME="IDX449"></A><P>Opening a file with the <CODE>fopen</CODE> function creates a new stream andestablishes a connection between the stream and a file. This mayinvolve creating a new file. <A NAME="IDX450"></A><P>Everything described in this section is declared in the header file<TT>`stdio.h'</TT>.<P><A NAME="IDX451"></A><U>Function:</U> FILE * <B>fopen</B> <I>(const char *<VAR>filename</VAR>, const char *<VAR>opentype</VAR>)</I><P>The <CODE>fopen</CODE> function opens a stream for I/O to the file<VAR>filename</VAR>, and returns a pointer to the stream.<P>The <VAR>opentype</VAR> 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:<P><DL COMPACT><DT><SAMP>`r'</SAMP><DD>Open an existing file for reading only.<P><DT><SAMP>`w'</SAMP><DD>Open the file for writing only. If the file already exists, it istruncated to zero length. Otherwise a new file is created.<P><DT><SAMP>`a'</SAMP><DD>Open 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.<P><DT><SAMP>`r+'</SAMP><DD>Open 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.<P><DT><SAMP>`w+'</SAMP><DD>Open file for both reading and writing. If the file already exists, itis truncated to zero length. Otherwise, a new file is created.<P><DT><SAMP>`a+'</SAMP><DD>Open or create file for both reading and appending. If the file exists,its initial contents are unchanged. Otherwise, a new file iscreated. The initial file position for reading might be at eitherthe beginning or end of the file, but output is always appendedto the end of the file.</DL><P>As you can see, <SAMP>`+'</SAMP> requests a stream that can do both input andoutput. When using such a stream, you must call <CODE>fflush</CODE>(see section <A HREF="library_11.html#SEC160" tppabs="http://www.cs.utah.edu/dept/old/texinfo/glibc-manual-0.02/library_11.html#SEC160">Stream Buffering</A>) or a file positioning function such as<CODE>fseek</CODE> (see section <A HREF="library_11.html#SEC158" tppabs="http://www.cs.utah.edu/dept/old/texinfo/glibc-manual-0.02/library_11.html#SEC158">File Positioning</A>) when switching from reading towriting or vice versa. Otherwise, internal buffers might not be emptiedproperly.<P>The GNU C library defines one additional character for use in<VAR>opentype</VAR>: the character <SAMP>`x'</SAMP> insists on creating a newfile--if a file <VAR>filename</VAR> already exists, <CODE>fopen</CODE> failsrather than opening it. This is equivalent to the <CODE>O_EXCL</CODE> optionto the <CODE>open</CODE> function (see section <A HREF="library_12.html#SEC184" tppabs="http://www.cs.utah.edu/dept/old/texinfo/glibc-manual-0.02/library_12.html#SEC184">File Status Flags</A>).<P>The character <SAMP>`b'</SAMP> in <VAR>opentype</VAR> 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>`+'</SAMP> and <SAMP>`b'</SAMP> are specified, they can appear in either order.See section <A HREF="library_11.html#SEC157" tppabs="http://www.cs.utah.edu/dept/old/texinfo/glibc-manual-0.02/library_11.html#SEC157">Text and Binary Streams</A>.<P>Any other characters in <VAR>opentype</VAR> are simply ignored. They may bemeaningful in other systems.<P>If the open fails, <CODE>fopen</CODE> returns a null pointer.<P>You 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. See section <A HREF="library_12.html#SEC176" tppabs="http://www.cs.utah.edu/dept/old/texinfo/glibc-manual-0.02/library_12.html#SEC176">Precautions for Mixing Streams and Descriptors</A>. 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. See section <A HREF="library_12.html#SEC185" tppabs="http://www.cs.utah.edu/dept/old/texinfo/glibc-manual-0.02/library_12.html#SEC185">File Locks</A>.<P><A NAME="IDX452"></A><U>Macro:</U> int <B>FOPEN_MAX</B><P>The value of this macro is an integer constant expression thatrepresents the minimum number of streams that the implementationguarantees can be open simultaneously. The value of this constant is atleast eight, which includes the three standard streams <CODE>stdin</CODE>,<CODE>stdout</CODE>, and <CODE>stderr</CODE>.<P><A NAME="IDX453"></A><U>Function:</U> FILE * <B>freopen</B> <I>(const char *<VAR>filename</VAR>, const char *<VAR>opentype</VAR>, FILE *<VAR>stream</VAR>)</I><P>This function is like a combination of <CODE>fclose</CODE> and <CODE>fopen</CODE>.It first closes the stream referred to by <VAR>stream</VAR>, ignoring anyerrors that are detected in the process. (Because errors are ignored,you should not use <CODE>freopen</CODE> on an output stream if you haveactually done any output using the stream.) Then the file named by<VAR>filename</VAR> is opened with mode <VAR>opentype</VAR> as for <CODE>fopen</CODE>,and associated with the same stream object <VAR>stream</VAR>.<P>If the operation fails, a null pointer is returned; otherwise,<CODE>freopen</CODE> returns <VAR>stream</VAR>.<P>The main use of <CODE>freopen</CODE> is to connect a standard stream such as<CODE>stdir</CODE> with a file of your own choice. This is useful in programsin which use of a standard stream for certain purposes is hard-coded.<P><H2><A NAME="SEC121" HREF="library_toc.html#SEC121" tppabs="http://www.cs.utah.edu/dept/old/texinfo/glibc-manual-0.02/library_toc.html#SEC121">Closing Streams</A></H2><A NAME="IDX454"></A><P>When a stream is closed with <CODE>fclose</CODE>, the connection between thestream and the file is cancelled. After you have closed a stream, youcannot perform any additional operations on it any more.<P><A NAME="IDX455"></A><U>Function:</U> int <B>fclose</B> <I>(FILE *<VAR>stream</VAR>)</I><P>This function causes <VAR>stream</VAR> 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</CODE> function returnsa value of <CODE>0</CODE> if the file was closed successfully, and <CODE>EOF</CODE>if an error was detected. <P>It is important to check for errors when you call <CODE>fclose</CODE> to closean output stream, because real, everyday errors can be detected at thistime. For example, when <CODE>fclose</CODE> writes the remaining bufferedoutput, it might get an error because the disk is full. Even if you youknow the buffer is empty, errors can still occur when closing a file ifyou are using NFS.<P>The function <CODE>fclose</CODE> is declared in <TT>`stdio.h'</TT>.<P>If the <CODE>main</CODE> function to your program returns, or if you call the<CODE>exit</CODE> function (see section <A HREF="library_22.html#SEC396" tppabs="http://www.cs.utah.edu/dept/old/texinfo/glibc-manual-0.02/library_22.html#SEC396">Normal Termination</A>), all open streams areautomatically closed properly. If your program terminates in any othermanner, such as by calling the <CODE>abort</CODE> function (see section <A HREF="library_22.html#SEC399" tppabs="http://www.cs.utah.edu/dept/old/texinfo/glibc-manual-0.02/library_22.html#SEC399">Aborting a Program</A>) or from a fatal signal (see section <A HREF="library_21.html#SEC330" tppabs="http://www.cs.utah.edu/dept/old/texinfo/glibc-manual-0.02/library_21.html#SEC330">Signal Handling</A>), open streamsmight not be closed properly. Buffered output may not be flushed andfiles may not be complete. For more information on buffering ofstreams, see section <A HREF="library_11.html#SEC160" tppabs="http://www.cs.utah.edu/dept/old/texinfo/glibc-manual-0.02/library_11.html#SEC160">Stream Buffering</A>.<P><H2><A NAME="SEC122" HREF="library_toc.html#SEC122" tppabs="http://www.cs.utah.edu/dept/old/texinfo/glibc-manual-0.02/library_toc.html#SEC122">Simple Output by Characters or Lines</A></H2><A NAME="IDX456"></A><P>This section describes functions for performing character- andline-oriented output. Largely for historical compatibility, there areseveral variants of these functions, but as a matter of style (and forsimplicity!) we suggest you stick with using <CODE>fputc</CODE> and<CODE>fputs</CODE>, and perhaps <CODE>putc</CODE> and <CODE>putchar</CODE>.<P>These functions are declared in the header file <TT>`stdio.h'</TT>.<A NAME="IDX457"></A><P><A NAME="IDX458"></A><U>Function:</U> int <B>fputc</B> <I>(int <VAR>c</VAR>, FILE *<VAR>stream</VAR>)</I><P>The <CODE>fputc</CODE> function converts the character <VAR>c</VAR> to type<CODE>unsigned char</CODE>, and writes it to the stream <VAR>stream</VAR>. <CODE>EOF</CODE> is returned if a write error occurs; otherwise thecharacter <VAR>c</VAR> is returned.<P><A NAME="IDX459"></A><U>Function:</U> int <B>putc</B> <I>(int <VAR>c</VAR>, FILE *<VAR>stream</VAR>)</I><P>This is just like <CODE>fputc</CODE>, except that most systems implement it asa macro, making it faster. One consequence is that it may evaluate the<VAR>stream</VAR> argument more than once.<P><A NAME="IDX460"></A><U>Function:</U> int <B>putchar</B> <I>(int <VAR>c</VAR>)</I><P>The <CODE>putchar</CODE> function is equivalent to <CODE>fputc</CODE> with<CODE>stdout</CODE> as the value of the <VAR>stream</VAR> argument.<P><A NAME="IDX461"></A><U>Function:</U> int <B>fputs</B> <I>(const char *<VAR>s</VAR>, FILE *<VAR>stream</VAR>)</I><P>The function <CODE>fputs</CODE> writes the string <VAR>s</VAR> to the stream<VAR>stream</VAR>. The terminating null character is not written.This function does <EM>not</EM> add a newline character, either.It outputs only the chars in the string.<P>This function returns <CODE>EOF</CODE> if a write error occurs, and otherwisea non-negative value.<P>
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -