basic_istream::read

To obtain a block of binary data from an input stream.

  basic_istream<charT, traits>& read
     (char_type* s, streamsize n);
  
Remarks

The function read() will attempt to extract a block of binary data until the following conditions are met.

A limit of n number of characters are stored.

end-of-file is encountered on the input (in which case setstate(failbit) is called.

Return

The this pointer is returned.

SeeAlso

basic_ostream::write

Listing: Example of basic_istream::read() usage:
#include <iostream>
#include <fstream>

#include <iomanip>

#include <cstdlib>

#include <cstring>

struct stock { 

   char name[80];

   double price;

   long trades;

};

char *Exchange = "BBSE";

char *Company = "Big Bucks Inc.";

int main()

{

using namespace std;

   stock Opening, Closing;

   strcpy(Opening.name, Company);

   Opening.price = 180.25;

   Opening.trades = 581300;

      // open file for output

   ofstream Market(Exchange, ios::out | ios::trunc | ios::binary); 

   if(!Market.is_open()) 

   {cout << "can't open file for output"; exit(1);}

   Market.write((char*) &Opening, sizeof(stock));

    Market.close();

         // open file for input

   ifstream Market2(Exchange, ios::in | ios::binary);

   if(!Market2.is_open()) 

   {cout << "can't open file for input"; exit(2);}

   Market2.read((char*) &Closing, sizeof(stock));

 

    cout << Closing.name << "\n"

      << "The number of trades was: " << Closing.trades << '\n';

   cout << fixed << setprecision(2)

      << "The closing price is: $" << Closing.price << endl;

   Market2.close();

   return 0;

}

Result:

  Big Bucks Inc.
  The number of trades was: 581300
  The closing price is: $180.25