C++ Files and Streams

So far, we have usediostreamthe standard library, which providescinandcoutThese methods are used to read streams from standard input and write streams to standard output, respectively.

This tutorial explains how to read streams from a file and write streams to a file. This requires another standard library in C++fstream, which defines three new data types:

Data types Description
ofstream This data type represents an output file stream and is used to create files and write information to files.
ifstream This data type represents an input file stream and is used to read information from files.
fstream This data type generally represents a file stream and has both ofstream and ifstream capabilities, meaning it can create files, write information to files, and read information from files.

To perform file processing in C++, you must include the header files <iostream> and <fstream> in your C++ source file.

Open a File

Before reading information from a file or writing information to a file, the file must first be opened.ofstreamandfstreamThese objects can be used to open files for write operations. If you only need to open a file for read operations, useifstreamObject.

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

void open(const char *filename, ios::openmode mode);

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

Mode Flags Description
ios::app Append mode. All writes are appended to the end of the file.
ios::ate Position to the end of the file after opening.
ios::in Open the file for reading.
ios::out Open the file for writing.
ios::trunc If the file already exists, its contents will be truncated before the file is opened, that is, the file length is set to 0.

You can combine two or more of the above modes. For example, if you want to open a file in write mode and truncate the file in case it already exists, you can use the following syntax:

ofstream outfile;
outfile.open("file.dat", ios::out | ios::trunc );

Similarly, if you want to open a file for reading and writing, you can use the following syntax:

ifstream  afile;
afile.open("file.dat", ios::out | ios::in );

Close a File

When a C++ program terminates, it automatically flushes all streams, releases all allocated memory, and closes all open files. However, programmers should develop the good habit of closing all open files before the program terminates.

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

void close();

Write to a File

In C++ programming, we use the stream insertion operator (<<) to write information to a file, just as we use this operator to output information to the screen. The only difference is that here you are usingofstreamorfstreamobject, rather thancoutObject.

Read from a File

In C++ programming, we use the stream extraction operator (>>) to read information from a file, just as we use this operator to input information from the keyboard. The only difference is that here you are usingifstreamorfstreamobject, rather thancinObject.

Read & Write Instance

The following C++ program opens a file in read/write mode. After writing user-input information to the file afile.dat, the program reads the information from the file and outputs it to the screen:

Example

#include <fstream> #include <iostream> using namespace std; int main() { char data[100]; // Open the file in write mode ofstream outfile; outfile.open("afile.dat"); cout << "Writing to the file" << endl; cout << "Enter your name: "; cin.getline(data, 100); // Write user input data to the file outfile << data << endl; cout << "Enter your age: "; cin >> data; cin.ignore(); // Write user input data to the file again outfile << data << endl; // Close the opened file outfile.close(); // Open the file in read mode ifstream infile; infile.open("afile.dat"); cout << "Reading from the file" << endl; infile >> data; // Write data to the screen cout << data << endl; // Read data from the file again and display it infile >> data; cout << data << endl; // Close the opened file infile.close(); return 0; }

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

$./a.out
Writing to the file
Enter your name: Zara
Enter your age: 9
Reading from the file
Zara
9

The above example uses additional functions of the cin object, such as the getline() function to read a line from external input, and the ignore() function to ignore extra characters left over from previous read statements.

File Position Pointer

istreamandostreamBoth provide member functions for repositioning the file position pointer. These member functions include, for istream,seekg("seek get") and about ostreamseekp("seek put")。

The parameters of seekg and seekp are usually a long integer. The second parameter can be used to specify the seek direction. The seek direction can beios::beg(by default, positioning from the beginning of the stream), or it can beios::cur(positioning from the current position in the stream), or it can beios::end(positioning starts from the end of the stream).

The file position pointer is an integer value that specifies the number of bytes from the start of the file to the position of the pointer. The following is an example of positioning the "get" file position pointer:

// Seek to the nth byte of fileObject (assuming ios::beg) fileObject.seekg( n ); // Move the file read pointer n bytes backward from the current position of fileObject fileObject.seekg( n, ios::cur ); // Move the file read pointer back n bytes from the end of fileObject fileObject.seekg( n, ios::end ); // Seek to the end of fileObject fileObject.seekg( 0, ios::end );
other extensions