What are the two methods of opening a file? Explain with examples. What is the difference between the two methods?
To open a file in a C++ program, we need to create a file stream which we can link to the file name. we can define a file stream using three different classes namely ifstream, ofstream and fstream that are all contained in the header file fstream. Which class to use shall depend upon the mode in which we want to open the file i.e, read or write. There are two modes to open a file.
1. Using the constructor function of the class
2. Using the member function “open()” of the class.
When using the first method that is constructor function of the class, we initialize the file stream object by file name. for example the following statement opens a file named “results” for input.
The syntax is as follows:
ifstream infile (“results”);
When using the second method of function “open()”, multiple files can be opened that use the same stream object for example when we wish to process a number of files in sequential manner, we shall create a single stream object and use it to open each file in turn.
The syntax is as follows:
file-stream-class stream-object;
stream-object.open(“filename”);
The basic difference between the two methods is that the constructor function of the class is used when we wish to open just one file in the stream. The open function is used when we wish to open multiple files using one stream.
Thanks
Mukesh Rajput
Post A Comment:
0 comments: