Opening Files in C++
Opening Files in C++:
Before reading data from or writing data into a file, the file must he opened. It is opened by creating objects of ifstream, ofstream or fstream stream classes.
A file is opened for output for writing data into it and it is also opened for input for reading data from it. Similarly, a file can also be opened for both input and output operations.
Opening Files in Output Mode:
To open a data file “filename” in output mode, an object of the ofstream (or fstream) class is created.
The syntax to open a data file for output is:
ofstream abc(filename, ios::out);
where:
abc is the name of the object of ofstream class that is to be created for controlling data streams.
filename It is specifies the name of the data tile that is to he opened. It may be a string constant or a string type variable. If a string constant is used, it is given in double quotes.
The “filename” in the name of the data tile that is to he associated with the object “abc”. The data into this file is written/read through the object associated with it.
ios::out It specifies the mode of operation of the file. The word “out” specifies that it is an output tile. The use of “ios::out” is optional if the object of ofstream class is being created. By default the objects of ofstream class are opened in output mode. Therefore, the above statement to open a data file for output can also he written as:
ofstream abc(filename);
The use of argument “filename” while creating an object of’ ofstream class is also optional. The object can be created even without opening a data file. The data file can be attached to the object later. For example to create an object “abc” of class ofstream, the statement is written as:
ofstream abc;
If the above statement is used then a data file can be attached with the created object afterwards. To attach a data file with the object “abc”, the member function “open” of I/O stream object is used. The syntax to attach the data file “filename” with the object “abc” is:
abc.open(filename, ios:out);
Opening Files in Input Mode:
To open a data file “filename” in input mode, an object of the ifstream (or fstream) class is created.
To create an object of ifstream class to open the file in input mode, the syntax is:
ifstream abc(filename, ios::in);
The arguments and other options for input mode are the same as mentioned in output mode.
