Swiftorial Logo
Home
Swift Lessons
Tutorials
Learn More
Career
Resources

Binary File I/O in C++

Introduction

File handling is an essential aspect of programming, allowing the storage and retrieval of data from files. In C++, file handling can be done using two types of files: text files and binary files. This tutorial focuses on binary file input and output (I/O) operations in C++.

Binary Files vs Text Files

Binary files store data in the same format as it is represented in memory, which makes them more efficient in terms of storage and performance. Text files, on the other hand, store data in human-readable form. When reading or writing binary files, you work with raw bytes rather than characters.

Including Necessary Headers

To work with files in C++, you need to include the appropriate headers. For binary file I/O, you primarily need the <fstream> header.

#include <fstream>
#include <iostream>

Opening a Binary File

To open a binary file, you need to create an instance of either std::ofstream (for writing) or std::ifstream (for reading), and specify the mode as binary using the std::ios::binary flag.

std::ofstream outFile("data.bin", std::ios::binary);
std::ifstream inFile("data.bin", std::ios::binary);

Writing to a Binary File

To write data to a binary file, you can use the write method of the std::ofstream class. The write method requires a pointer to the data and the size of the data in bytes.

struct Data {
    int id;
    char name[20];
    float score;
};

Data d = {1, "John Doe", 95.5};

std::ofstream outFile("data.bin", std::ios::binary);
outFile.write(reinterpret_cast<char*>(&d), sizeof(d));
outFile.close();

Reading from a Binary File

To read data from a binary file, you can use the read method of the std::ifstream class. Similar to the write method, the read method requires a pointer to a buffer where the data will be stored and the size of the data in bytes.

struct Data {
    int id;
    char name[20];
    float score;
};

Data d;

std::ifstream inFile("data.bin", std::ios::binary);
inFile.read(reinterpret_cast<char*>(&d), sizeof(d));
inFile.close();

std::cout << "ID: " << d.id << "\n";
std::cout << "Name: " << d.name << "\n";
std::cout << "Score: " << d.score << "\n";

Checking for Errors

It's important to check for errors when performing file operations. You can use the fail method to check if an operation failed.

if (outFile.fail()) {
    std::cerr << "Error writing to file\n";
}

if (inFile.fail()) {
    std::cerr << "Error reading from file\n";
}

Example Program

Here's a complete example program that demonstrates both writing to and reading from a binary file.

#include <fstream>
#include <iostream>

struct Data {
    int id;
    char name[20];
    float score;
};

int main() {
    Data d1 = {1, "John Doe", 95.5};

    // Writing to a binary file
    std::ofstream outFile("data.bin", std::ios::binary);
    if (outFile.fail()) {
        std::cerr << "Error opening file for writing\n";
        return 1;
    }
    outFile.write(reinterpret_cast<char*>(&d1), sizeof(d1));
    outFile.close();

    // Reading from a binary file
    Data d2;
    std::ifstream inFile("data.bin", std::ios::binary);
    if (inFile.fail()) {
        std::cerr << "Error opening file for reading\n";
        return 1;
    }
    inFile.read(reinterpret_cast<char*>(&d2), sizeof(d2));
    inFile.close();

    // Displaying the read data
    std::cout << "ID: " << d2.id << "\n";
    std::cout << "Name: " << d2.name << "\n";
    std::cout << "Score: " << d2.score << "\n";

    return 0;
}

Conclusion

Binary file I/O in C++ is a powerful feature that allows efficient storage and retrieval of data. By understanding the concepts of writing to and reading from binary files, you can handle complex data structures and ensure data integrity during I/O operations.