devxlogo

Writing Binary Data to an ofstream

Writing Binary Data to an ofstream

To write the binary value of a variable to an output file stream (ofstream) object, use the write() member function. write() takes two parameters: const char * and long, which hold the address of the variable being written to the file and its size, respectively. The following code snippet writes the binary value of an int to a file:

 int n=100;ofstream results("numbers.dat");results.write(reinterpret_cast  (&n), sizeof(n));

write() returns a reference to ofstream so you can chain several input operations as follows:

 results.write(&c, sizeof(c)).write(&d, sizeof(d));

devx-admin

Share the Post: