devxlogo

Reading Binary Data from an ifstream

Reading Binary Data from an ifstream

To read a binary value from an input file stream (ifstream) object, use the read() member function. read() takes two parameters: char * and long, which hold the address of the buffer to which the value is written and its size, respectively. The following code snippet retrieves an int from a file and copies it to m:

 int m;ifstream results("numbers.dat");results.read(reinterpret_cast  (&m), sizeof(m));

read() returns a reference to ifstream so you retrieve multiple values as follows:

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

devx-admin

Share the Post: