Introduction to C++ | File Handling and Streams

File Handling and Streams in C++

File handling in C++ is a powerful feature that allows you to read from and write to files. It is crucial for storing and manipulating data beyond program execution. C++ provides an easy-to-use mechanism for file I/O (input/output) through the fstream library, which supports various file stream operations like reading, writing, and modifying files.

What are Streams?

Streams in C++ represent the flow of data to and from a source (like a file, keyboard, or screen). Streams are divided into two categories:

File Handling in C++

In C++, file handling is done using the fstream library, which provides classes for handling file streams:

Opening and Closing a File

Files are opened using the open() function, and you can specify the mode (input, output, or both) when opening a file. After performing operations on the file, you should always close it using close().

Example of Writing to a File

This example demonstrates writing data to a file using ofstream.

Code Example


        #include <iostream>
        #include <fstream>
        
        using namespace std;  
        int main () {  
          ofstream filestream("example.txt");  
          if (filestream.is_open())  
          {  
            filestream << "Welcome to Shorat.n";  
            filestream << "C++ Tutorial.n";  
            filestream.close();  
          }  
          else cout <<"File opening is fail.";  
          return 0;  
        }  
                            

Output

The content of a text file example.txt is set with the data: Welcome to Shorat. C++ Tutorial.

Reading from a File

To read data from a file, use ifstream (input file stream). You can read data line by line or word by word, depending on your needs.

Example of Reading from a File

This example demonstrates how to read from a file using ifstream.

Code Example


        #include <iostream>
        #include <fstream>
        using namespace std;  
        int main () {  
          string srg;  
          ifstream filestream("example.txt");  
          if (filestream.is_open())  
          {  
            while ( getline (filestream,srg) )  
            {  
              cout << srg <<endl;  
            }  
            filestream.close();  
          }  
          else {  
              cout << "File opening is fail."<<endl;   
            }  
          return 0;  
        }  
                            

Output

Welcome to Shorat. C++ Tutorial.

File Open Modes

When opening a file, you can specify the mode in which you want to open the file. Here are the most common file open modes:

Example: File Opening with Different Modes

Here’s an example showing how to open a file with different modes:

Code Example: File Open Modes


        #include <iostream>
        #include <fstream>
        
            int main() {
                // Open a file for appending
                std::ofstream outFile("example.txt", std::ios::out | std::ios::app);
            
                // Check if the file opened successfully
                if (!outFile) {
                    std::cerr << "Error: Could not open the file!" << std::endl;
                    return 1;
                }
            
                // Append text to the file
                outFile << "Appending some more text to the file." << std::endl;
            
                // Close the file
                outFile.close();
            
                std::cout << "Text appended successfully." << std::endl;
            
                return 0;
            }
                                

Pro Tip:

💡 Pro Tip

When working with files, always check if the file opened successfully. Use error-handling techniques such as if (!file) to avoid runtime errors. Also, always close the file after you are done with it to release system resources.