Opening and Closing Files in C++
In C++, opening of files can be achieved in two ways:
- Using the constructor function of the stream class.
- Using the function open.
The first method is preferred when a single file is used with a stream, however, for managing multiple files with the same stream, the second method is preferred.
- Opening files using Constructors
The data being read from DataFile has been channelised through the input stream as shown:
The above given statement creates an object (input_file) of input file stream. The object name is a user defined name. After creating the ifstream object input_file, the file DataFile is opened and attached to the input stream input_file. Now both, the data being read from DataFile has been channelised through the input stream object. The connections with a file are closed automatically when the input and output stream objects expire i.e., when they go out of scope. (For instance, a global object expires when the program terminates). Also you can close a connection with a file explicitly by using close method
input_file.close;Closing such a connection does not eliminate the stream, it just disconnects it from the file. The stream still remains there. Closing a file flushes the buffer which means the data remaining in the buffer (input or output stream) is moved out of it in the direction it is ought to be.
- Opening files using open function
A stream can be connected to only one file at a time.
Read more about this topic: Data File
Famous quotes containing the words opening, closing and/or files:
“They said to each other, Were not our hearts burning within us while he was talking to us on the road, while he was opening the scriptures to us?”
—Bible: New Testament, Luke 24:32.
The Emmaus story.
“At closing time would go
In waders and peaked cap
Into the showery dark,
A dole-kept breadwinner
But a natural for work.”
—Seamus Heaney (b. 1939)
“The good husband finds method as efficient in the packing of fire-wood in a shed, or in the harvesting of fruits in the cellar, as in Peninsular campaigns or the files of the Department of State.”
—Ralph Waldo Emerson (18031882)