Sams Teach Yourself C++ in 21 Days

(singke) #1
open and close files, you create ifstreamand ofstreamobjects as described in the next
few sections.

Using the ofstream..............................................................................................


The particular objects used to read from or write to files are called ofstreamobjects.
These are derived from the iostreamobjects you’ve been using so far.
To get started with writing to a file, you must first create an ofstreamobject, and then
associate that object with a particular file on your disk. To use ofstreamobjects, you
must be certain to include fstreamin your program.

624 Day 17


Because fstreamincludes iostream, you do not need to include iostream
explicitly.

NOTE

Condition States..............................................................................................


The iostreamobjects maintain flags that report on the state of your input and output.
You can check each of these flags using the Boolean functions eof(),bad(),fail(),
and good(). The function eof()returns trueif the iostreamobject has encountered
EOF, end of file. The function bad()returns trueif you attempt an invalid operation.
The function fail()returns trueanytime bad()is true or an operation fails. Finally, the
function good()returns trueanytime all three of the other functions are false.

Opening Files for Input and Output ..............................................................


To use a file, you must first open it. To open the file myfile.cppwith an ofstream
object, declare an instance of an ofstreamobject and pass in the filename as a
parameter:
ofstream fout(“myfile.cpp”);
This attempts to open the file,myfile.cpp, for output. Opening this file for input works
the same way, except that it uses an ifstreamobject:
ifstream fin(“myfile.cpp”);
Note that foutand finare names you define; here,fouthas been used to reflect its sim-
ilarity to cout, and finhas been used to reflect its similarity to cin. These could also be
given names that reflect what is in the file they are accessing.
Free download pdf