C++ file streams can be used to read and write class objects directly using the read() and write() functions. This allows an object's data to be stored in a binary file and later loaded back into an object.
- write() stores the raw bytes of an object in a file, while read() loads them back into an object.
- This approach is suitable for classes containing trivially copyable data members; classes with std::string or pointers should not be serialized this way.
Example:
Input: Input.txt contains contestant records with name, age, and rating.
Operation: Find the contestant with the highest rating.
Output: Terry
write() and read() Syntax
The basic syntax for writing and reading an object is:
file.write(reinterpret_cast<char*>(&obj), sizeof(obj));
file.read(reinterpret_cast<char*>(&obj), sizeof(obj));
Approach to Read and Write Class Objects
The object can be written to a binary file using write() and read back using read(). However, directly writing an object containing std::string is not safe or portable, because it contains internal pointers and implementation-specific data. For a safe binary-file example, use a class with fixed-size character data and primitive data members.
- Define a class with trivially copyable data members.
- Create an object and assign values to its members.
- Open the file in binary output mode.
- Write the object using write().
- Open the file in binary input mode.
- Read each object using read().
- Process the objects as required.
- Close the file after reading or writing.
#include <iostream>
#include <fstream>
#include <cstring>
using namespace std;
class Contestant
{
public:
char name[20];
int age;
int rating;
};
int main()
{
// Create and write objects to the file
ofstream outFile("Input.txt", ios::binary);
Contestant c1 = {"Michael", 19, 1806};
Contestant c2 = {"Kemp", 24, 2114};
Contestant c3 = {"Terry", 21, 2400};
outFile.write(reinterpret_cast<char*>(&c1), sizeof(c1));
outFile.write(reinterpret_cast<char*>(&c2), sizeof(c2));
outFile.write(reinterpret_cast<char*>(&c3), sizeof(c3));
outFile.close();
// Read objects from the file
ifstream inFile("Input.txt", ios::binary);
Contestant c;
Contestant highest;
bool found = false;
while (inFile.read(reinterpret_cast<char*>(&c), sizeof(c)))
{
if (!found || c.rating > highest.rating)
{
highest = c;
found = true;
}
}
inFile.close();
if (found)
cout << highest.name;
return 0;
}
Output
Terry
Explanation: Each Contestant object is stored in binary form using write(). The objects are then read back using read(), and the contestant with the highest rating is selected.
Note: Direct binary serialization using read() and write() should not be used for classes containing non-trivially copyable members such as std::string, std::vector, or raw pointers. For such classes, serialize each data member separately or use an appropriate serialization format.