ios::binary
argument when opening
// Open a binary file for input ifstream fin; fin.open("image.bmp", ios::binary);
read(char* var, int num_bytes)
var
char*
, typecast into a char pointer
// Read 4 bytes into the integer int num; fin.read((char*) &num, 4);
read
calls
// Read pointer advances 4 bytes after the read fin.read((char*) &num, 4);
seekg(int byte_offset)
before reading from the file
// Move to the beginning of the file fin.seekg(0); // Read the first 4 bytes into an integer fin.read((char*) &num, 4); // Move the pointer to the 100 byte offset fin.seekg(100); // Read the next 4 bytes into an integer fin.read((char*) &num, 4);
ios::binary
argument when opening
// Open a binary file for output ofstream fout; fout.open("image.bmp", ios::binary);
write(char* variable, int num_bytes)
variable
to the file
char*
, type caste into a char pointer
// Write the integer to file int num = 15; fout.write((char*) &num, 4);
write
calls
// Write pointer advances 4 bytes after the write fout.write((char*) &num, 4);
seekp(int byte_offset)
before writing to the file
// Move to the beginning of the file fout.seekp(0); // Write the integer to the first 4 bytes fout.write((char*) &num, 4); // Move the pointer to the 100 byte offset fout.seekp(100); // Write the integer to the next 4 bytes fout.write((char*) &num, 4);