How to Write Binary File in C++: Syntax and Example
To write a binary file in C++, use
std::ofstream with the std::ios::binary flag to open the file in binary mode. Then use the write() method to write raw bytes to the file.Syntax
Use std::ofstream with std::ios::binary to open a file for binary writing. The write() function takes a pointer to a character buffer and the number of bytes to write.
std::ofstream file(<filename>, std::ios::binary);: Opens the file in binary mode.file.write(const char* buffer, std::streamsize size);: Writessizebytes frombufferto the file.file.close();: Closes the file (optional, done automatically on destruction).
cpp
std::ofstream file("filename.bin", std::ios::binary); file.write(reinterpret_cast<const char*>(&data), sizeof(data)); file.close();
Example
This example writes an integer array to a binary file named numbers.bin. It opens the file in binary mode, writes the raw bytes of the array, and closes the file.
cpp
#include <iostream> #include <fstream> int main() { int numbers[] = {10, 20, 30, 40, 50}; std::ofstream file("numbers.bin", std::ios::binary); if (!file) { std::cerr << "Error opening file for writing." << std::endl; return 1; } file.write(reinterpret_cast<const char*>(numbers), sizeof(numbers)); file.close(); std::cout << "Binary file written successfully." << std::endl; return 0; }
Output
Binary file written successfully.
Common Pitfalls
- Not opening the file with
std::ios::binarycauses data to be written in text mode, which can corrupt binary data. - Forgetting to use
reinterpret_cast<const char*>when passing data towrite()leads to compilation errors. - Writing pointers instead of the data they point to writes memory addresses, not the actual data.
- Not checking if the file opened successfully can cause silent failures.
cpp
#include <fstream> // Wrong: Missing binary mode // std::ofstream file("data.bin"); // Correct: // std::ofstream file("data.bin", std::ios::binary); // Wrong: Passing pointer without cast // file.write(numbers, sizeof(numbers)); // Correct: // file.write(reinterpret_cast<const char*>(numbers), sizeof(numbers));
Quick Reference
Remember these key points when writing binary files in C++:
- Always open the file with
std::ios::binary. - Use
reinterpret_cast<const char*>to convert data pointers forwrite(). - Write the exact number of bytes you want to save.
- Check if the file opened successfully before writing.
Key Takeaways
Open files with std::ios::binary to write raw bytes correctly.
Use reinterpret_cast to convert data pointers for writing.
Always check if the file opened successfully before writing.
Write the exact byte size of the data to avoid corruption.
Close the file or let the destructor handle it to flush data.