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 < 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));
See also  How College Students Can Shape the Future of Tech Responsibility
devxblackblue

About Our Editorial Process

At DevX, we’re dedicated to tech entrepreneurship. Our team closely follows industry shifts, new products, AI breakthroughs, technology trends, and funding announcements. Articles undergo thorough editing to ensure accuracy and clarity, reflecting DevX’s style and supporting entrepreneurs in the tech sphere.

See our full editorial policy.

About Our Journalist