How to Read Binary File in C++: Syntax and Example
To read a binary file in C++, open an
std::ifstream with the std::ios::binary flag. Then use read() to load bytes into a buffer or variable. Always check if the file opened successfully before reading.Syntax
Use std::ifstream to open the file in binary mode with std::ios::binary. Then call read() to read raw bytes into a buffer.
std::ifstream file(filename, std::ios::binary);opens the file.file.read(buffer, size);readssizebytes intobuffer.- Always check
file.is_open()to confirm the file opened.
cpp
std::ifstream file("filename.bin", std::ios::binary); if (file.is_open()) { char buffer[100]; file.read(buffer, sizeof(buffer)); // process buffer file.close(); }
Example
This example reads 4 bytes from a binary file named data.bin and prints their integer values.
cpp
#include <iostream> #include <fstream> int main() { std::ifstream file("data.bin", std::ios::binary); if (!file.is_open()) { std::cerr << "Failed to open file.\n"; return 1; } char buffer[4]; file.read(buffer, 4); if (file.gcount() < 4) { std::cerr << "Could not read 4 bytes.\n"; return 1; } std::cout << "Read bytes as integers: "; for (int i = 0; i < 4; ++i) { std::cout << static_cast<int>(static_cast<unsigned char>(buffer[i])) << " "; } std::cout << "\n"; file.close(); return 0; }
Output
Read bytes as integers: 72 101 108 108
Common Pitfalls
- Not opening the file with
std::ios::binarycauses data corruption on some systems. - Failing to check if the file opened leads to runtime errors.
- Reading more bytes than the file contains causes incomplete data reads.
- Using text mode can alter line endings and corrupt binary data.
cpp
/* Wrong way: missing binary mode */ std::ifstream file("data.bin"); // no std::ios::binary /* Right way: specify binary mode */ std::ifstream file("data.bin", std::ios::binary);
Quick Reference
| Step | Description |
|---|---|
| Open file | std::ifstream file("file.bin", std::ios::binary); |
| Check open | if (!file.is_open()) { handle error } |
| Read data | file.read(buffer, size); |
| Check bytes read | file.gcount() returns bytes actually read |
| Close file | file.close(); |
Key Takeaways
Always open binary files with std::ios::binary flag to avoid data corruption.
Use std::ifstream::read() to read raw bytes into a buffer.
Check if the file opened successfully before reading.
Verify the number of bytes read with gcount() to handle short reads.
Close the file after finishing reading to free resources.