|
 |
|
 |
by John
Kopp
Welcome to About.com's tutorial on C++ programming. This
lesson covers file input and output, and iostream
manipulators. Learning how to read and write files is an
important step in learning any programming language. Any real
world application is likely to process large amounts of
information. A simple technique to transfer and record data is
via files. More advanced techniques for data storage and
manipulation can involve the use of relational databases or
special data formats such as XML. For now, we will study the
use of text files.
One important issue with writing
results to output files is data format. Whether the ultimate
consumer of a programs output be man or machine, the format of
this output can be as significant as its content. If the
output is being consumed by another program, then the output
format is likely to be predetermined and highly specific in
order for the consuming program to be able to properly read
and access the data. If the output file is to be read by
people, data format can significantly influence understanding
and utility. Iostream manipulators provide a way to control
output format.
File Input and Output The techniques
for file input and output, i/o, in C++ are virtually identical
to those introduced in earlier lessons for writing and reading
to the standard output devices, the screen and keyboard. To
perform file input and output the include file fstream must be
used.
Fstream contains class
definitions for classes
used in file i/o. Within a program needing file i/o, for each
output file required, an object of class ofstream is instantiated.
For each input file required, an object
of class ifstream is instantiated. The ofstream object is used
exactly as the cout object for standard output is used. The
ifstream object is used exactly as the cin object for standard
input is used. This is best understood by studying an
example.
#include <iostream> #include
<fstream> using namespace std;
int
main() { ofstream
myFile("c:/out.txt"); //
Creates an ofstream object named
myFile
if (! myFile)
// Always test file
open { cout
<< "Error opening output file" <<
endl; return
-1; }
myFile
<< "Hello World" <<
endl;
myFile.close();
return
0; } | Let's examine this
program. The first step created an ofstream object named
myFile.
The constructor
for the ofstream class takes two arguments. The first
specifies a file name as a C-style string, the second a file
mode. There are two common file open modes, truncate and
append. By default, if no mode is specified and the file
exists, it is truncated. The mode is specified by using an
enumerator define in the ios class. The ios class contains
members which describe modes and states for the input and
output classes. An enumeration
is a way to define a series of constants. Please see the lesson
on constants for more detail. Fortunately, all this boils down
to something very simple.
|