Posted By:
4 Jul, 2013 1:33 pm PDT

Opening and closing a file in C++

How to open and close a file? What are the different file mode parameters available?

If you want to open a file just to read the contents in it, then you can use ifstream. The format for using ifstream is:

ifstream <stream_name> <stream_name>.open ('<file_name>.ext');


If you want to open a file to write to it, then you can use ofstream. If you want to read as well as write into it you can fstream. The format for ofstream and fstream is same as that of ifstream. While opening the file we can include mode parameters along with the file name.

The different file mode parameters available in C++ are:



ios::app - Append to end of file

ios::ate - goto end of file on opening

ios::binary - binary file

ios::trunc - deletes contents if it exits

ios::nocreate - open fails if file doesn't exist

ios::noreplace - open fails if file already exists

ios::in - opens existing file for reading it

ios::out - creates new file for writing on


You can a close a file by using <stream_name>.close()

Was it useful?  

Please login to reply to this problem.