Binary File I/O
Read and write raw bytes.
Text vs Binary
Text mode writes human-readable characters; binary mode writes the raw bytes of objects exactly as they sit in memory. Open with std::ios::binary.
#include <iostream>
#include <fstream>
int main() {
int value = 12345;
std::ofstream out("v.bin", std::ios::binary);
out.write(reinterpret_cast<const char*>(&value), sizeof(value));
std::cout << "wrote " << sizeof(value) << " bytes\n";
return 0;
}write Takes Bytes
write(ptr, n) outputs n raw bytes from ptr. You cast the object address to const char*.
#include <iostream>
#include <fstream>
int main() {
double d = 3.14;
std::ofstream out("d.bin", std::ios::binary);
out.write(reinterpret_cast<const char*>(&d), sizeof(d));
out.close();
std::cout << "saved a double\n";
return 0;
}