C++ Files and Streams

    By using the cout<< and cin>> statements of the iostream header file, we can take input and show output data to the user. However, in C++, we have a concept known as file handling that allows us to use a C++ program to create a file that can store data in text format, even if the program is terminated. This tutorial on C++ files and streams will teach you how to create, read, and write files in C++. So, let's get started!

    File Handling in C++

    In C++, we can use files to store the data permanently. File handling provides us with a technique to create, read, and write files. The input-output operation in C++ uses the iostream library. Similarly, file operations in C++ also use some libraries, such as fstream, ifstream, and ofstream, and these streams provide an interface between files and programs.

    File Streams:

    • ifstream

    It is an input file stream class and it provides input operations for the file. With ifstream we can access get(), getline(), read(), seekg() and tellg() functions to perform the read operations. It is used to read from an existing file.

    • ofstream

    It is an output file stream and it provides output operations for the file. ofstream provides various methods or functions like put(), write(), tellp() and seekp(). Also, it is used to create a new file or write something new in the file.

    • fstream

    It is an input-output stream and it inherits all the properties of the ifstream and ofstream class. With fstream, we can perform both read and write operations on a file.

    Data Files

    As file handling is all about creating files to store data permanently for later use, we can store data in the following two types of file formats:

    • Text file
    • Binary File

    Text File

    In C++, we mostly use the text file to store the information in file handling. In a text file, all the data is stored in ASCII characters, and we can simply open the text file and read data from it because the data is in a human-readable form. Moreover, there are multiple lines in a text file with each line terminated with a special character known as End of Line(EOL).

    Binary File

    A binary file stores information in binary format ( binary data ), which is not in a human-readable form. In a binary file, the data stored is in the same format as it is stored in the computer memory. We do not require any translation in binary files, which makes them faster as compared to the text files.

    File Handling Operations:

    With file handling, we can perform 4 operations on files:

    • Create a file or open a file
    • Write to a file
    • Read from file
    • Close the file

    1. Open A file

    Before opening a file, we need to mention the stream for the file. If we want to read data from an existing file, we use the ifstream . On the other hand, if we want to write into a file or want to create a new file, we use ofstream. Also, we can use the fstream for both read and write operations. If we want to perform any operation on the file, such as read from the file or write in a file, we need to open the file. If the file is not already in the memory, we cannot use the ifstream . In such a case, we have to use the ofstream or fstream to create a new file. Once we have mentioned a stream, we need to open the file for the read and write operations. To open or create a new file, we use the open() method. Syntax to Open a File:

    stream_name file_object;
    file_object.open(“file_name”, File_mode)

    Example :

    #include <iostream>
    #include <fstream>
    using namespace std;
    int main()
    {
       ofstream file;   // stream of the file is ofstream
       file.open("New_File.txt",ios::out);  // this will create a new txt file by name NEW_FILE
    }

    Behind the Code: This code will create a new text file in the same folder where the program file is saved. Here we have not performed any operation on the file, and that’s why the file is empty. If you run this program twice, it will not create a new file; it just simply opens the existing one. Here we have used the ofstream because if the file is not already present in the memory, it will create one by the name NEW_File .

    ofstream file

    Here we have created a stream object of the ofstream class, and by using ofstream , we have set an output stream for the file object . file.open("New_File.txt",ios::out); With the file object, we used the open function which accepts two arguments - file name and file mode . Here, the file name is New_File.txt and the file mode is ios::out .

    File Mode

    The file mode describes how a file is to be used. Also, it decides whether we should read from the file or write in the file or append to the file. There are various file modes present for the open() function, and the file mode we pass in the open function must have corresponded to its stream type.

    File Modes Description Stream type
    ios::in Opens the file to read (default for ifstream). ifstream
    Ios::out Opens the file to write (default for ofstream). ofstream, ifstream
    ios::app Opens the file and appends all the outputs at the end. ofstream
    ios::ate Opens the file and moves the control to the end of the file. ofstream, ifstream
    ios::trunc Removes the data in the existing file. ofstream
    ios::nocreate It throws an error if the file is not already existing in the memory. This mode is used when we do not want to create a new file and want to perform the read and write operation on the existing file. ofstream
    ios::noreplace If the file already exists, it will throw an error. This mode is used when we want to create a new file. ofstream
    ios::binary Opens the file in binary mode ofstream, ifstream

    By default, all the file modes open the text files. If you want to open the binary file, you need to mention the binary mode.

    2. Write to a File

    Once a file is created or opened, we can write in the file. To write in a file, we require the stream object of ofstream or fstream. The streams that we can use to write files in C++ are as follows:

    • fstream
    • ofstream

    Example:

    #include <iostream>
    #include <fstream>
    using namespace std;
    int main()
    {
    fstream file;
    file.open("NEW_FILE.txt",ios::out);  //mode is ios::out  
    file<<"This data has been stored in the file";    //writing in the file
    cout<<"The above statement has been written in NEW_FILE.txt";
    file.close();   // to close the open file   
    return 0;
    }

    Output:

    The above statement has been written in NEW_FILE.txt

    In NEW_FILE.txt:

    This data has been stored in the file

    Behind the Code: In the above code, we firstly set the stream object. After that, by using the stream object, we opened the file. Here, the file mode is ios::out , which means we can only write in the file. Using the file stream object file and insertion pointer << , we write the statement in the file. Note: If you run the above program, again and again, the statement file<<"This data has been stored in the file”; will override the file. If you want to append the file data, change the file mode from ios::out to ios::app.

    3. Read From a File

    Once we have created a file and written something in it, then only we can perform the read operation on it. To perform a read operation on a file or to read data from a file, we need to create an object of the file with an input stream using the fstream or ifstream. Example:

    #include <iostream>
    #include <fstream>
    using namespace std;
    int main()
    {
    char line[100];
    ifstream file;
    file.open("NEW_FILE.txt",ios::in);  //mode is ios::in  
    file.getline(line,80);       //reading a line from a file.
    cout<<line;                    //showing the line
    file.close();                     // to close the open file
    return 0;
    }

    Output:

    This data has been stored in the file

    Behind the Code: In the above example, we open the file in ios::in mode, which means that we can perform the read operation on the NEW_FILE.txt . Once the file is opened using the getline(line,80) method or function of the ifstream class, we can read the first 80 characters of the file NEW_FILE.txt, and save those characters in a string line.

    4. Close a File

    If we open a file, we need to close it too. In the above examples, if you do not even close the file, it will not affect the program. However, when we deal with multiple file open statements in one program, we do require the close() function to close a file. Example:

    file.open("NEW_FILE.txt",ios::in);  //mode is ios::in  
    file.close();                     // to close the open file

    File Handling Quick Summary

    • File handling gives us a technique to store program data in a text or binary file.
    • By default, we use the text file to store the data.
    • Before we create a new file or open the existing one, we require to declare the file stream.
    • There are 3 basic file streams that we can use in C++: fstream, ofstream, and ifstream.
    • ofstream is used to write in the file, ifstream is used to read from a file, and fstream can be used for both.
    • We can create a file only with the help of ofstream and stream.
    • To open and create a file, we use the open() method.
    • With the open method, we pass two arguments: file name and file mode.
    • File mode describes the operation that can be performed on the file.

    To Conclude it All

    We hope that this tutorial helped you develop a better understanding of the C++ Files and Streams. Also, we have discussed how you can perform 4 different file operations, namely open a file, write to a file, read from a file, and close a file. If you have any queries or questions related to C++ Files and Streams, let us know by posting them in the comments section below. People are also reading: