Open a file

July 31st, 2010 c# No comments

ios::in Open for input operations.

ios::out Open for output operations.

ios::binary Open in binary mode.

ios::ate Set the initial position at the end of the file.
If this flag is not set to any value, the initial position is the beginning of the file.

ios::app All output operations are performed at the end of the file, appending the content to the current content of the file. This flag can only be used in streams open for output-only operations.

ios::trunc If the file opened for output operations already existed before, its previous content is deleted and replaced by the new one.
All these flags can be combined using the bitwise operator OR (|). For example, if we want to open the file example.bin in binary mode to add data we could do it by the following call to member function open():
ofstream myfile; (“example.bin”, ios::out | ios::app | ios::binary);
Each one of the open() member functions of the classes ofstream, ifstream and fstream has a default mode that is used if the file is opened without a second argument:

class default mode parameter
ofstream ios::out
ifstream ios::in
fstream ios::in | ios::out

To check if a file stream was successful opening a file, you can do it by calling to member is_open() with no arguments. This member function returns a bool value of true in the case that indeed the stream object is associated with an open file, or false otherwise:

if (myfile.is_open()) { /* ok, proceed with output */ }

Categories: C++ Standard Library Tags: