C++ provides the <fstream> library to interact with binary files, particularly the “ofstream” class, for writing the binary data. This capability allows the developers to seamlessly create, modify, and manage the binary files. This article explores the various methods and techniques for writing the binary files in C++, shedding light on their applications and use cases.
Write a Binary File Using C++
To save the data into a binary file using C++, the write() method is employed. This function writes a specified number of bytes to the designated stream, beginning at the location of the “put” pointer. If the “put” pointer is at the end, the file is extended. However, the new data overwrites the existing characters if the pointer is within the file. In the event of an error during the writing process, the stream is marked as being in an error state. Now, let us move on to the examples to learn how to write in a binary file using some simple and built in C++ functions.
Method 1: Writing Binary Files with Structured Data
You may need to write a structured data, such as custom structures, to a binary file in many cases. Let’s consider an example that contains a record of a person which includes the name, height, and age of a person. See the following given code and have a look at the explanation:
#include <fstream>
struct Person {
char name[50];
int age;
double height;
};
int main() {
std::ofstream outFile("people.bin", std::ios::binary);
if (!outFile.is_open()) {
std::cerr << "Error! Can't open file for writing!" << std::endl;
return 1;
}
Person person1 = {"Kalsoom Ilyas", 25, 1.75};
Person person2 = {"Kalsoom Bajwa", 30, 1.68};
outFile.write(reinterpret_cast<char*>(&person1), sizeof(person1));
outFile.write(reinterpret_cast<char*>(&person2), sizeof(person2));
outFile.close();
std::cout << "The person's record is written to binary file successfully." << std::endl;
return 0;
}
Here’s a breakdown of the code with the specific details. The program begins with defining a custom structure named “Person”. It has three fields: name, age, and height. The details of these fields are as follows:
- name: A string to store the person’s name (up to 50 characters)
- age: An integer to store the person’s age
- height: A double to store the person’s height
After defining the “Person” structure, the main function starts which is the program’s entry point. The first line in the main program opens a file named “people.bin”. We use “std::ofstream” to create a file named “people.bin” for writing the data in binary format. Checking if the file opens successfully is very important. Otherwise, an error message is shown and the program stops. Hence, with the help of the “if” condition and is_open() function, we check whether the file has opened successfully or not.
Here, the two “Person” objects are created. We define two variables, “person1” and “person2”, of “Person” type. We assign the variable name, age, and height values for “Kalsoom Ilyas” and “Kalsoom Bajwa”.
Now that we have the data to write in a binary file, let us perform the actual function with the write() function. We use the “outFile.write” to write the contents of each “Person” object to the file. The “reinterpret_cast<char*>(&person1)” and “reinterpret_cast<char*>(&person2)” convert the entire “Person” structure (including all its fields) into a continuous stream of bytes that is suitable for writing to the binary file. We write the size of each “Person” object using the “sizeof(person1)” and “sizeof(person2)” to ensure that all data is written correctly.
After writing the data on the file, it is very important to close it properly so that no data will get lost due to any other function. We use outFile.close() to release the resources that are associated with the file and ensure that the data is written accurately. Finally, we print a message that confirms the data’s successful writing to the binary file.
If we explain this example in simpler terms, imagine a special notebook that can only store an information about people in a secret language. This code creates a blueprint for organizing the information (name, age, height). It opens the notebook, fills out the profiles for two people, translates the information into the secret language, and writes it neatly inside. It then closes the notebook securely, preserving the profiles for future use. Refer to the output of the program that is given in the following snapshot:
Method 2: Writing Integers to a Binary File
In this method, an array of integers is written to a binary file named “integers.bin”. The “reinterpret_cast<char*>” treats the integer array as a sequence of characters (bytes) for writing into the file. This is especially important as binary files deal with raw byte data. Let us have a look at the following simple example:
#include <fstream>
int main() {
std::ofstream outFile("integers.bin", std::ios::binary);
if (!outFile.is_open()) {
std::cerr << "Error! Can't open file for writing!" << std::endl;
return 1;
}
int numbers[] = {42, 99, -1, 0};
outFile.write(reinterpret_cast<char*>(numbers), sizeof(numbers));
outFile.close();
std::cout << "The given integers written to binary file successfully." << std::endl;
return 0;
}
Here’s a breakdown of the code with the specific details:
The “#include <iostream>” and “#include <fstream>” bring in the necessary tools for working with files and printing the messages like cin and write(), respectively. The “std::ofstream outFile(“integers.bin”, std::ios::binary);” opens a binary file named “integers.bin” that can only store the numbers in a secret code (binary format). It checks if the file is open. Otherwise, an error message is given.
The next line which is “int numbers[] = {42, 99, -1, 0};” defines an array named “numbers” with integers 42, 99, -1, and 0. The “outFile.write(reinterpret_cast<char*>(numbers), sizeof(numbers));” carefully translates the integers into the binary format and writes them in the “integer.bin” file. The “outFile.close();” closes the file correctly to keep the integers safe and organized. Finally, a message is printed to confirm that the integers have been successfully stored in the binary file. Refer to the following output of this program to see the result:
Conclusion
Writing binary files in C++ is a crucial skill to efficiently handle the various types of data. In this exploration of writing binary files in C++, we’ve learned how the “ofstream” class can be employed to handle the binary data efficiently. Whether dealing with simple integers or structured data using custom structures, the process involves opening a file stream, writing the data in binary format, and then closing the file. This capability provides the C++ developers with the flexibility to work with a diverse range of binary data types, contributing to the versatility of the language in applications that range from system-level programming to multimedia processing.