⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 tut6-1.html

📁 a Complete C++ language tutorial on the cplusplus.com
💻 HTML
📖 第 1 页 / 共 2 页
字号:
<HTML>
<HEAD>
<TITLE>C++ tutorial: 6.1, Input/Output with files</TITLE>
<META NAME="description" CONTENT="Use of file streams">
<META NAME="keywords" CONTENT="fstream open close">
</HEAD>

<BODY BGCOLOR="white">

<!--captut-->
<CENTER>
<TABLE WIDTH=100% CELLPADDING=0 CELLSPACING=1 BORDER=0>
<TR><TD WIDTH=90%>
 <FONT SIZE=4> Section 6.1 </FONT><BR>
 <FONT SIZE=5><B>Input/Output with files</B></FONT>
</TD><TD><!--ad--><!--#include virtual="/ad/ad468.shtml"--><!--/ad-->
</TD><TD VALIGN="bottom"><A HREF="http://www.cplusplus.com/doc/tutorial/">
 <IMG SRC="head.gif" ALT="cplusplus.com" BORDER=0></A></TD></TR>
<TR><TD BGCOLOR="#0000FF" ALIGN="center" COLSPAN=3>
 <IMG SRC="head0.gif" WIDTH=2 HEIGHT=2 BORDER=0></TD></TR>
</TABLE>
</CENTER>
<!--/captut-->

<P>
C++ has support both for input and output with files through the following classes:
<UL>
<LI><TT><B>ofstream:</B></TT> File class for writing operations (derived from <TT>ostream</TT>)
<LI><TT><B>ifstream:</B></TT> File class for reading operations (derived from <TT>istream</TT>)
<LI><TT><B>fstream: </B></TT> File class for both reading and writing operations (derived from <TT>iostream</TT>)
</UL>

<P>
<H2>Open a file</H2>
The first operation generally done on an object of one of these classes is to associate it
to a real file, that is to say, to open a file.  The open file is represented
within the program by a stream object (an instantiation of one of these classes) and any
input or output performed on this stream object will be applied to the physical file.
<P>
In order to open a file with a stream object we use its member function <TT><B>open()</B></TT>:
<BLOCKQUOTE><TT><PRE>
<B>void open (const char * </B><I>filename</I><B>, openmode</B><I> mode</I><B>);</B>
</PRE></TT></BLOCKQUOTE>
where <TT><I>filename</I></TT> is a string of characters representing the name of the
file to be opened and <TT><I>mode</I></TT> is a combination of the following flags:<BR>
<BLOCKQUOTE><TABLE BORDER=1>
<TR><TD><TT><B>ios::in</B></TT></TD><TD>Open file for reading</TD></TR>
<TR><TD><TT><B>ios::out</B></TT></TD><TD>Open file for writing</TD></TR>
<TR><TD><TT><B>ios::ate</B></TT></TD><TD>Initial position:  end of file</TD></TR>
<TR><TD><TT><B>ios::app</B></TT></TD><TD>Every output is appended at the end of file</TD></TR>
<TR><TD><TT><B>ios::trunc</B></TT></TD><TD>If the file already existed it is erased</TD></TR>
<TR><TD><TT><B>ios::binary</B></TT></TD><TD>Binary mode</TD></TR>
</TABLE></BLOCKQUOTE>
These flags can be combined using bitwise operator OR: <TT><B>|</B></TT>.
For example, if we want to open the file "example.bin" in binary mode to add data
we could do it by the following call to function-member <TT><B>open</B></TT>:
<BLOCKQUOTE><TT>
ofstream file;<BR>
file.open ("example.bin", ios::out | ios::app | ios::binary);
</TT></BLOCKQUOTE>
All of the member functions <TT><B>open</B></TT> of classes
<TT><B>ofstream</B></TT>, <TT><B>ifstream</B></TT> and <TT><B>fstream</B></TT>
include a default mode when opening files that varies from one to the other:
<BLOCKQUOTE><TABLE BORDER=1>
<TR><TD BGCOLOR="silver">class</TD><TD BGCOLOR="silver">default <I>mode</I> to parameter</TD></TR>
<TR><TD><TT><B>ofstream</B></TT></TD><TD><TT>ios::out | ios::trunc</TT></TD></TR>
<TR><TD><TT><B>ifstream</B></TT></TD><TD><TT>ios::in</TT></TD></TR>
<TR><TD><TT><B>fstream</B></TT></TD><TD><TT>ios::in | ios::out</TT></TD></TR>
</TABLE></BLOCKQUOTE>
The default value is only applied if the function is called <U>without</U> specifying a
<TT><I>mode</I></TT> parameter. If the function is called with any value in that parameter
the default mode is stepped on, not combined.

<P>
Since the first task that is performed on an object of classes
<TT><B>ofstream</B></TT>, <TT><B>ifstream</B></TT> and <TT><B>fstream</B></TT>
is frequently to open a file, these three classes include a constructor that directly calls 
the <TT><B>open</B></TT> member function and has the same parameters as this.  This way,
we could also have declared the previous object and conducted the same opening operation
just by writing:
<BLOCKQUOTE><TT>
ofstream file ("example.bin", ios::out | ios::app | ios::binary);
</TT></BLOCKQUOTE>
Both forms to open a file are valid.

<P>
You can check if a file has been correctly opened by calling the member function
<TT><B>is_open()</B></TT>:
<BLOCKQUOTE><TT>bool is_open();</TT></BLOCKQUOTE>
that returns a <TT><B>bool</B></TT> type value indicating <TT><B>true</B></TT> in case that
indeed the object has been correctly associated with an open file or <TT><B>false</B></TT>
otherwise.

<P>
<H2>Closing a file</H2>
When reading, writing or consulting operations on a file are complete we must close it
so that it becomes available again. In order to do that we shall call the member function
<TT><B>close()</B></TT>, that is in charge of flushing the buffers and closing the file.
Its form is quite simple:
<BLOCKQUOTE><TT><B>void close ();</B></TT></BLOCKQUOTE>
Once this member function is called, the stream object can be used to open another file,
and the file is available again to be opened by other processes.
<P>
In case that an object is destructed while still associated with an open file,
the destructor automatically calls the member function  <TT><B>close</B></TT>.
<P>
<H2>Text mode files</H2>
Classes <TT><B>ofstream</B></TT>, <TT><B>ifstream</B></TT> and <TT><B>fstream</B></TT>
are derived from <TT><B>ostream</B></TT>, <TT><B>istream</B></TT> and <TT><B>iostream</B></TT>
respectively. That's why <I>fstream</I> objects can use the members of these parent classes
to access data.
<P>
Generally, when using text files we shall use the same members of these classes that
we used in communication with the console (<TT><B>cin</B></TT> and <TT><B>cout</B></TT>).
As in the following example, where we use the overloaded insertion operator
<TT><B>&lt;&lt;</B></TT>:
<P>
<CENTER>
<TABLE WIDTH=100% CELLPADDING=5 CELLSPACING=5><TR><TD BGCOLOR="#FFFFBF" WIDTH=50% VALIGN="top">
<TT><PRE><I>// writing on a text file</I>
#include &lt;fstream.h&gt;

int main () {
  ofstream examplefile ("example.txt");
  if (examplefile.is_open())
  {
    examplefile &lt;&lt; "This is a line.\n";
    examplefile &lt;&lt; "This is another line.\n";
    examplefile.close();
  }
  return 0;
}
</PRE></TT>
</TD><TD BGCOLOR="silver" WIDTH=50% VALIGN="top">
<TABLE WIDTH=100% CELLSPACING=5><TR><TD BGCOLOR="white"><FONT COLOR="green"><CENTER><TT>file <B>example.txt</B></TT></CENTER></FONT></TD></TR></TABLE>
<TT><B>
This is a line.<BR>
This is another line.
</B></TT>
</TD></TR></TABLE>
</CENTER>
<P>
Data input from file can also be performed in the same way that we did with
<TT><B>cin</B></TT>:

<P>
<CENTER>
<TABLE WIDTH=100% CELLPADDING=5 CELLSPACING=5><TR><TD BGCOLOR="#FFFFBF" WIDTH=50% VALIGN="top">
<TT><PRE><I>// reading a text file</I>
#include &lt;iostream.h&gt;
#include &lt;fstream.h&gt;
#include &lt;stdlib.h&gt;

int main () {
  char buffer[256];
  ifstream examplefile ("example.txt");
  if (! examplefile.is_open())
  { cout &lt;&lt; "Error opening file"; exit (1); }

  while (! examplefile.eof() )
  {
    examplefile.getline (buffer,100);
    cout &lt;&lt; buffer &lt;&lt; endl;
  }
  return 0;
}
</PRE></TT>
</TD><TD BGCOLOR="silver" WIDTH=50% VALIGN="top"><TT>
<B>This is a line.<BR>
This is another line.</B>
</TT></TD></TR></TABLE>
</CENTER>
<P>
This last example reads a text file and prints out its content on the screen.
Notice how we have used a new member function, called <TT><B>eof</B></TT>
that <TT><B>ifstream</B></TT> inherits from class <TT><B>ios</B></TT> and that
returns <TT><B>true</B></TT> in case that the end of the file has been reached.

<P>
<H2>Verification of state flags</H2>
In addition to <TT><B>eof()</B></TT>, other member functions exist
to verify the state of the stream (all of them return a <TT><B>bool</B></TT> value):
<DL>
<DT><TT><B>bad()</B></TT>
<DD>Returns <TT><B>true</B></TT> if a failure occurs in a reading or writing operation.
For example in case we try to write to a file that is not open for writing or if the device
where we try to write has no space left.
<DT><TT><B>fail()</B></TT>
<DD>Returns <TT><B>true</B></TT> in the same cases as <TT><B>bad()</B></TT> plus
in case that a format error happens, as trying to read an integer number and
an alphabetical character is received.
<DT><TT><B>eof()</B></TT>
<DD>Returns <TT><B>true</B></TT> if a file opened for reading has reached the end.
<DT><TT><B>good()</B></TT>

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -