Reading from and Writing to Files in C++


In C++, file handling is an important feature that allows you to read from and write to files. This is achieved using file streams, which are part of the <fstream> header file. In this article, we will explore how to read from and write to files using ifstream, ofstream, and fstream classes.

Reading from Files in C++

To read data from a file in C++, you use the ifstream class. The ifstream (input file stream) class is derived from the istream class and is used to perform input operations on files.

Example: Reading Text from a File

    #include <iostream>
    #include <fstream>

    int main() {
        std::ifstream inFile("example.txt");  // Open file for reading

        if (inFile.is_open()) {
            std::string line;
            
            // Read the file line by line
            while (getline(inFile, line)) {
                std::cout << line << std::endl;  // Print each line
            }
            inFile.close();  // Close the file
        } else {
            std::cout << "Unable to open file" << std::endl;
        }
        return 0;
    }
        

In this example, we open the file example.txt using the ifstream class. If the file is successfully opened, we use the getline() function to read the file line by line. Each line is printed to the console. After reading the file, we close it using the close() method.

Writing to Files in C++

To write data to a file in C++, you use the ofstream class. The ofstream (output file stream) class is derived from the ostream class and provides methods to write data to a file.

Example: Writing Text to a File

    #include <iostream>
    #include <fstream>

    int main() {
        std::ofstream outFile("example.txt");  // Open file for writing

        if (outFile.is_open()) {
            outFile << "Hello, C++ File Handling!" << std::endl;  // Write data to the file
            outFile.close();  // Close the file
            std::cout << "Data written to file successfully!" << std::endl;
        } else {
            std::cout << "Unable to open file for writing" << std::endl;
        }
        return 0;
    }
        

In this example, we open the file example.txt using the ofstream class. If the file is successfully opened, we write the string "Hello, C++ File Handling!" to the file. After writing the data, we close the file.

Reading and Writing to Files Using fstream

If you want to read from and write to the same file, you can use the fstream class. The fstream class is derived from both ifstream and ofstream, enabling bidirectional file operations.

Example: Reading from and Writing to a File Using fstream

    #include <iostream>
    #include <fstream>

    int main() {
        std::fstream file("example.txt", std::ios::in | std::ios::out);  // Open file for both reading and writing

        if (file.is_open()) {
            std::string line;
            
            // Read the file content
            getline(file, line);
            std::cout << "File content: " << line << std::endl;

            // Write to the file
            file.seekp(0);  // Move write pointer to the beginning of the file
            file << "Updated file content!" << std::endl;

            file.close();  // Close the file
        } else {
            std::cout << "Unable to open file" << std::endl;
        }
        return 0;
    }
        

In this example, we use the fstream class to open the file example.txt for both reading and writing. We first read the content of the file and display it on the console, then we use the seekp() method to move the write pointer to the beginning of the file to overwrite the existing content with new data.

Working with Binary Files

C++ allows you to read from and write to binary files using file streams. To do this, you use the std::ios::binary mode when opening a file. This ensures that the data is written and read in binary format, rather than as text.

Example: Writing to a Binary File

    #include <iostream>
    #include <fstream>

    int main() {
        std::ofstream outFile("binaryfile.dat", std::ios::binary);  // Open file for binary writing

        if (outFile.is_open()) {
            int number = 12345;
            outFile.write(reinterpret_cast(&number), sizeof(number));  // Write binary data
            outFile.close();  // Close the file
            std::cout << "Binary data written to file successfully!" << std::endl;
        } else {
            std::cout << "Unable to open binary file for writing" << std::endl;
        }
        return 0;
    }
        

In this example, we open a binary file binaryfile.dat and write an integer value to the file using the write() function. The reinterpret_cast(&number) is used to convert the integer to a character pointer, allowing it to be written as raw binary data.

Example: Reading from a Binary File

    #include <iostream>
    #include <fstream>

    int main() {
        std::ifstream inFile("binaryfile.dat", std::ios::binary);  // Open file for binary reading

        if (inFile.is_open()) {
            int number;
            inFile.read(reinterpret_cast(&number), sizeof(number));  // Read binary data
            std::cout << "Read number: " << number << std::endl;
            inFile.close();  // Close the file
        } else {
            std::cout << "Unable to open binary file for reading" << std::endl;
        }
        return 0;
    }
        

In this example, we open the binary file binaryfile.dat for reading. We use the read() function to read the binary data into an integer variable and display the result on the console.

Conclusion

In C++, reading from and writing to files is an essential aspect of file handling. By using file stream classes such as ifstream, ofstream, and fstream, you can easily manage files in your programs. Whether you're working with text or binary files, C++ provides the necessary tools to handle a variety of file operations. Always remember to close the file after performing operations to ensure that resources are properly released.





Advertisement