Browse DevX
Sign up for e-mail newsletters from DevX

Tip of the Day
Language: C++
Expertise: Intermediate
Jan 4, 2002



Building the Right Environment to Support AI, Machine Learning and Deep Learning

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 < char * > (&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));
Danny Kalev
Thanks for your registration, follow us on our social networks to keep up-to-date