Easy Tutorial
❮ Cpp Examples Cout Helloworld C Function Difftime ❯

C++ Files and Streams

So far, we have used the iostream standard library, which provides cin and cout methods for reading from standard input and writing to standard output, respectively.

This tutorial introduces how to read from and write to files. This requires using another standard library in C++ called fstream, which defines three new data types:

Data Type Description
ofstream This data type represents an output file stream for creating files and writing information to them.
ifstream This data type represents an input file stream for reading information from files.
fstream This data type typically represents a file stream and has both ofstream and ifstream capabilities, meaning it can create files, write information to them, and read information from them.

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

Opening a File

Before reading from or writing to a file, you must open it. ofstream and fstream objects can be used to open files for writing, and if you only need to open a file for reading, use an ifstream object.

Here 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, the first parameter of the open() 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 Flag Description
ios::app Append mode. All writes are appended to the end of the file.
ios::ate The file is opened and positioned at 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, setting the file length to 0.

You can combine two or more of these modes. For example, if you want to open a file in write mode and truncate it if 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 both reading and writing, you can use the following syntax:

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

Closing a File

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

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

void close();

Writing to a File

In C++ programming, we use the stream insertion operator (<<) to write information to a file, just as we use it to output information to the screen. The only difference is that here you use an ofstream or fstream object instead of a cout object.

Reading from a File

In C++ programming, we use the stream extraction operator (>>) to read information from a file, just as we use it to input information from the keyboard. The only difference is that here you use an ifstream or fstream object instead of a cin object.

Reading & Writing Example

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

Example

#include <fstream>
#include <iostream>
using namespace std;

int main ()
{
    char data[100];

    // Open 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 to the file
    outfile << data << endl;

    cout << "Enter your age: "; 
    cin >> data;
    cin.ignore();

    // Write user input to the file again
    outfile << data << endl;

    // Close the opened file
    outfile.close();

    // Open file in read mode
    ifstream infile; 
    infile.open("afile.dat"); 

    cout << "Reading from the file" << endl; 
    infile >> data; 

    // Write the data at the screen
    cout << data << endl;

    // Read the data from the file and write it to the screen
    infile >> data; 
    cout << data << endl; 

    // Close the opened file
    infile.close();

    return 0;
}
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 the outside, and the ignore() function to ignore any extra characters left by previous read statements.

File Position Pointer

Both istream and ostream provide member functions for repositioning the file position pointer. These member functions include seekg ("seek get") for istream and seekp ("seek put") for ostream.

The parameters for seekg and seekp are typically a long integer. The second parameter can be used to specify the search direction. The search direction can be ios::beg (default, starting from the beginning of the stream), ios::cur (starting from the current position of the stream), or ios::end (starting 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 pointer's position. Below is an example of positioning the "get" file position pointer:

// Position at the nth byte of fileObject (assuming ios::beg)
fileObject.seekg(n);

// Move the file's read pointer n bytes forward from the current position of fileObject
fileObject.seekg(n, ios::cur);

// Move the file's read pointer n bytes backward from the end of fileObject
fileObject.seekg(n, ios::end);

// Position at the end of fileObject
fileObject.seekg(0, ios::end);
❮ Cpp Examples Cout Helloworld C Function Difftime ❯