C++ Reading and Writing Binary Files
In C++, you can read and write binary files using the fstream
class, which provides a convenient way to read and write from a file as if it were a stream. To read and write binary data to a file, you first need to create an fstream
object and associate it with a file.
Here's an example of how to write binary data to a file:
refer t:otheitroad.com#include <fstream> #include <iostream> int main() { std::fstream outfile("example.bin", std::ios::out | std::ios::binary); if (!outfile) { std::cerr << "Failed to open file for writing" << std::endl; return 1; } int numbers[] = { 1, 2, 3, 4, 5 }; outfile.write((const char*) numbers, sizeof(numbers)); outfile.close(); return 0; }
In this example, we first create an fstream
object called outfile
and associate it with the file "example.bin". We then check to make sure that the file was opened successfully, and if not, we print an error message and return from the program.
We then define an integer array called numbers
with some sample data. We use the write()
method to write the entire contents of this array to the file. The write()
method takes a const char*
buffer and a length, so we use a cast to convert the int*
array to a const char*
buffer and the sizeof
operator to get the length.
Finally, we close the file using the close()
method.
When the program is run, it will open the file "example.bin" and write the contents of the numbers
array to it in binary form.
You can also use fstream
to read binary data from a file:
#include <fstream> #include <iostream> int main() { std::fstream infile("example.bin", std::ios::in | std::ios::binary); if (!infile) { std::cerr << "Failed to open file for reading" << std::endl; return 1; } int numbers[5]; infile.read((char*) numbers, sizeof(numbers)); infile.close(); for (int i = 0; i < 5; i++) { std::cout << numbers[i] << std::endl; } return 0; }
In this example, we first create an fstream
object called infile
and associate it with the file "example.bin". We then check to make sure that the file was opened successfully, and if not, we print an error message and return from the program.
We then define an integer array called numbers
. We use the read()
method to read the entire contents of the file into this array. The read()
method takes a char*
buffer and a length, so we use a cast to convert the int*
array to a char*
buffer and the sizeof
operator to get the length.
Finally, we close the file using the close()
method, and output the contents of the numbers
array to the console.
In summary, to read and write binary data to a file in C++:
- Create an
fstream
object and associate it with a file using the file name and the appropriate file mode (usuallystd::ios::in
for reading orstd::ios::out
for writing, along withstd::ios::binary
for binary data). - Check to make sure that the file was opened successfully.
- Read or write data to the file using