next up previous
Next: Reading and Writing Text Up: File I/O Previous: File I/O

Opening and Closing a File

In C++, a file is opened by linking it to a stream. There are three types of streams: input, output and input/output. To open an input stream you must declare the stream to be of class ifstream. To open an output stream, it must be declared as class ofstream. A stream that will be be performing both input and output operations must be declared as class fstream. For example, this fragment creates one input stream, one output stream and one stream that is capable of both input and output.

ifstream in;
ofstream out;
fstream both;

Once you have created s stream, one way to associate it with a file is by using open(). This function is a member of each of the three stream classes. Its prototype is shown here

void open(const char *filename, int mode, int access);

Here, filename is the name of the file. The value of the mode determines how the file is opened. It must be one or more of the following values which are defined in the fstream.h

ios::app // causes all output to the file to be appended to the end
ios::ate // causes a seek to the end of the file occur when file is opened
ios::binary// causes a file to be opened in binary mode
ios::out // specifies that the file is capable of output
ios::in// specifies that the file is capable of input
ios::nocreate// causes open() to fail if the file doe not already exist.
ios::noreplace// causes open() to fail if the file already exist
ios::trunc// causes the contents of a preexisting file by the same name to be destroyed and truncate the file to zero length

The value of access determines how the file can be accessed. In DOS/Windows environments, this value generally corresponds to the DOS/Windows file attribute code listed here:


Attribute Meaning
  Norma file; open access
1 read-only file
2 hidden file
4 system file
8 archive bit set


The following fragment opens a normal output file

ofstream out;
out.open("test",ios::out,o);

The default value for mode is ios::out for ofstream and ios::in for ifstream and the default value for access is 0. Hence the previous statement can be written as

out.open("test");

To open a stream for input and output, you must specify both ios::in and ios::out mode values as shown here,

fstream xyst;
xyst.open("test",ios::in | ios::out);

To close a file, use the member function close(). For example to close the file linked to a stream called xyst you would use this statement

xyst.close();
The close function takes no parameters and returns no values.


next up previous
Next: Reading and Writing Text Up: File I/O Previous: File I/O
Yousef Haik
2/23/1998