File Handling and Streams in C++ - The Mode Flags
(Page 3 of 4 )
Each time you open a file via a stream, the open procedure and how the file behaves are all controlled via some internal flags of the fstream class. Even when you specify nothing clearly, the default values will be used. The file modes are just integer values essentially, so we can combine them with a bitwise operator.
Here is a list of what's available and their effects on the file stream:
=> in - open for input
=> out - open for output
=> app - seek to the end before every write
=> ate -seek to the end immediately after the open
=> trunc - truncate an existing stream when opening it
=> binary - do the I/O procedures in binary mode (the stream will consist of ones and zeros)
Of course, not all of them have the same effect on the three types of file streams, and some do not even have a specific sense. The trunk flag will eventually delete the previous data inside the file. Opening an ofstream file with just the out flag works essentially just as if you had declared the trunk flag also, as it would clear anything that had been there before.
The solution, if you only want to append into the file, is to use the app flag with the ofstream. In the case of the fstream, the trunc is no longer there by default, so all of the previous data inside the file will remain.
Next: The Binary Flag >>
More C++ Articles
More By Gabor Bernat