In this tutorial, we will learn how to perform binary file Input/Output (I/O) operations in C++. Binary file I/O allows for a more efficient and precise way to store and retrieve data. By the end of this tutorial, you will be able to read from and write to binary files using C++.
Prerequisites: Basic knowledge of C++ programming and familiarity with basic file I/O operations.
Binary files store data in a binary format, which is the same format in which the data is held in memory. Unlike text files, binary files are not human-readable. When we say binary files, it generally refers to data files that contain data, not readable characters.
To read and write in binary mode, the file stream objects have the member function open()
, which accepts an additional argument for mode. The modes are defined in the ios class, which is the base class for all the file streams in C++. To open a file in binary mode, we use the ios::binary mode.
To read from a binary file, follow these steps:
To write to a binary file, follow these steps:
#include <fstream>
#include <iostream>
int main() {
int number = 12345;
std::ofstream outputFile;
// Open the file in binary mode
outputFile.open("output.bin", std::ios::binary);
// Write to the file
outputFile.write((char*)&number, sizeof(number));
outputFile.close();
return 0;
}
This program writes an integer to a binary file. outputFile.write((char*)&number, sizeof(number));
writes the binary representation of number
to the file.
#include <fstream>
#include <iostream>
int main() {
int number;
std::ifstream inputFile;
// Open the file in binary mode
inputFile.open("output.bin", std::ios::binary);
// Read from the file
inputFile.read((char*)&number, sizeof(number));
std::cout << "The number is: " << number << std::endl;
inputFile.close();
return 0;
}
This program reads an integer from a binary file. inputFile.read((char*)&number, sizeof(number));
reads the binary data from the file into number
.
The number is: 12345
In this tutorial, we learned how to perform binary file I/O in C++. We learned how to write to and read from binary files using the write()
and read()
member functions of the fstream library.
For further practice, try the following exercises:
Remember, practicing and experimenting is the key to learning programming. Good luck!