Modes of Opening Files
When you open a file (for writing or
reading), there are 6 modes that you can use to specify how you want the file to
be opened. The modes are :
ios::app
ios::ate
ios::binary
ios::in
ios::out
ios::trunc
Including ios::app
causes all the output (or whatever you write) to be appended to the end
of the file. This mode can be used only for files opened for output.
ios::in specifies that the file is capable of
input only. ios::out specifies that the file is
capable of output.
ios::binary causes the file to be opened in binary
mode (I'll deal with binary later on).
ios::trunc causes contents of pre-existing file by
same name to be destroyed.
So far we've seen the file opening as follows :
ofstream out;
out.open("test");
// This means test is opened in normal mode.
By default this is the same as out.open("test",
ios::out);
// opened specifically for output
We can combine two modes as follows :
out.open("test", ios::out | ios::binary );
What is Binary?
Reading
and writing formatted text is easy. But sometimes you may need to store
unformatted data (i.e. in binary or raw form) and not as text. In the next
section I'll deal with such functions. When you perform binary operations on a
file, you should open it in binary mode. If a file is opened in text mode (or
normal mode) and you make use of these functions (that are intended for binary
mode), the functions will work. But some character translations will
occur.
Basically there are two types of files that C++ recognizes : binary and text
files. Binary files can contain any data representation format. Text files
contain only alphanumeric data as represented by the compiler's character set
(for example ASCII). By default, all files are opened in text mode unless you
specify ios::binary.
Next section we shall take a look at : Put ( ) and Get ( ) functions
or Go back to Contents Page 2.