Data File - Opening and Closing Files in C++

Opening and Closing Files in C++

In C++, opening of files can be achieved in two ways:

  1. Using the constructor function of the stream class.
  2. 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
ifstream input_file("DataFile");

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
ifstream filin; //create an input stream filin.open("Master.dat"); //associate '''filin''' stream with file Master.dat . //process Master.dat . filin.close; //terminate association with Master.dat filin.open("Tran.dat"); //associate '''filin''' stream with file Tran.dat . //process Tran.dat . filin.close; //terminate association

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:

    And then ... he flung open the door of my compartment, and ushered in “Ma young and lovely lady!” I muttered to myself with some bitterness. “And this is, of course, the opening scene of Vol. I. She is the Heroine. And I am one of those subordinate characters that only turn up when needed for the development of her destiny, and whose final appearance is outside the church, waiting to greet the Happy Pair!”
    Lewis Carroll [Charles Lutwidge Dodgson] (1832–1898)

    And if the stage-dark head rehearse
    The fifth act of the closing night,
    Why, cut it off, piece after piece,
    And throw the tough cortex away....
    Allen Tate (1899–1979)

    But some who this blithe mood present,
    As on in lightsome files they fare,
    Shall die experienced ere three days be spent—
    Perish, enlightened by the vollied glare;
    Or shame survive, and, like to adamant,
    Thy after shock, Manassas, share.
    Herman Melville (1819–1891)