Thinking in C++ Vol 2 - Practical Programming |
Prev |
Home |
Next |
You can control the way a file is opened by overriding the
constructor s default arguments. The following table shows the flags that
control the mode of the file:
Flag
|
Function
|
ios::in
|
Opens an input file. Use this as an open mode for an ofstream
to prevent truncating an existing file.
|
ios::out
|
Opens an output file. When used for an ofstream
without ios::app, ios::ate or ios::in, ios::trunc
is implied.
|
ios::app
|
Opens an output file for appending only.
|
ios::ate
|
Opens an existing file (either input or output) and seeks
to the end.
|
ios::trunc
|
Truncates the old file if it already exists.
|
ios::binary
|
Opens a file in binary mode. The default is text
mode.
|
You can combine these flags using a bitwise or
operation.
The binary flag, while portable, only has an effect on some
non-UNIX systems, such as operating systems derived from MS-DOS, that have special
conventions for storing end-of-line delimiters. For example, on MS-DOS systems
in text mode (which is the default), every time you output a newline character ('\n'), the file system actually outputs two characters, a
carriage-return/linefeed pair (CRLF), which is the pair of ASCII characters 0x0D
and 0x0A. Conversely, when you read such a file back into memory in text
mode, each occurrence of this pair of bytes causes a '\n' to be sent to
the program in its place. If you want to bypass this special processing, you
open files in binary mode. Binary mode has nothing whatsoever to do with
whether you can write raw bytes to a file you always can (by
calling write( )) . You should, however, open a file in binary mode
when you ll be using read( ) or write( ), because these
functions take a byte count parameter. Having the extra '\r' characters
will throw your byte count off in those instances. You should also open a file
in binary mode if you re going to use the stream-positioning commands discussed
later in this chapter.
You can open a file for both input and output by declaring
an fstream object. When declaring an fstream object, you must use
enough of the open mode flags mentioned earlier to let the file system know
whether you want to input, output, or both. To switch from output to input, you
need to either flush the stream or change the file position. To change from
input to output, change the file position. To create a file via an fstream
object, use the ios::trunc open mode flag in the constructor call to do
both input and output.
Thinking in C++ Vol 2 - Practical Programming |
Prev |
Home |
Next |