Mastery 28

Reading and writing of files in C++

Opening a File:

A file must be opened before you can read from it or write to it. Either the ofstream or fstreamobject may be used to open a file for writing and ifstream object is used to open a file for reading purpose only.

Following is the standard syntax for open() function, which is a member of fstream, ifstream, and ofstream objects.

Here, the first argument specifies the name and location of the file to be opened and the second argument of the open() member function defines the mode in which the file should be opened.

Mode Flag Description
ios::app Append mode. All output to that file to be appended to the end.
ios::ate Open a file for output and move the read/write control to the end of the file.
ios::in Open a file for reading.
ios::out Open a file for writing.
ios::trunc If the file already exists, its contents will be truncated before opening the file.

You can combine two or more of these values by ORing them together. For example if you want to open a file in write mode and want to truncate it in case it already exists, following will be the syntax:

Similar way, you can open a file for reading and writing purpose as follows:

Closing a File

When a C++ program terminates it automatically closes flushes all the streams, release all the allocated memory and close all the opened files. But it is always a good practice that a programmer should close all the opened files before program termination.

Following is the standard syntax for close() function, which is a member of fstream, ifstream, and ofstream objects.

Writing to a File:

While doing C++ programming, you write information to a file from your program using the stream insertion operator (ofstream or fstream object instead of the cout object.

Reading from a File:

You read information from a file into your program using the stream extraction operator (>>) just as you use that operator to input information from the keyboard. The only difference is that you use an ifstream or fstream object instead of the cin object.

Read & Write Example:

Following is the C++ program which opens a file in reading and writing mode. After writing information inputted by the user to a file named afile.dat, the program reads information from the file and outputs it onto the screen:

When the above code is compiled and executed, it produces the following sample input and output:

Above examples make use of additional functions from cin object, like getline() function to read the line from outside and ignore() function to ignore the extra characters left by previous read statement.

Credits:

http://www.tutorialspoint.com/cplusplus/cpp_files_streams.htm

1017 28

CC BY 4.0 Mastery 28 by Mauricio Cooper is licensed under a Creative Commons Attribution 4.0 International License.

Comments are closed.