How to open and close a file in C++?

To open a file you first have to link that particular file to a stream. So, a stream which can be input, output or both input/output is found to open a file. An input stream can be created by declaring:

ifstream in;

An output stream can be created by declaring:

ofstream out;

An input/output stream can be created by declaring:

fstream io;

When the stream is created, open() function is used:

For input stream:

void ifstream::open(const char *f, ios::openmode mode = ios::in);

For output stream:

void ofstream::open(const char *f, ios::openmode mode = ios::out | ios::trunc);

For input/output stream:

void fstream::open(const char *f, ios::openmode mode = ios::in | ios::out);

where, f is name of file.

Values of mode can be anything given below. These values can be combined by performing OR operation:

ios::in – This value shows that input operation can be performed.

ios::out – This value shows that output operation can be performed.

ios::trunc – This value is used to truncate any previous files with same names.

ios::app: – This value is used to append the output to the end of file.

ios::ate  – This value is used to seek the end of a file.

ios::binary – This value is used to open a file in binary. Default file opening is in text.

Hence to open a general input file:

ofstream in;“moreprocess”);

To close a file, use the syntax:


where, test_stream is the stream to which the file is linked to.

Leave a Reply