Inserts a block of binary data into an output stream.
basic_ostream<charT, traits>& write (const char_type* s, streamsize n);
The overloaded function write() is used to insert a block of binary data into a stream. This function can be used to write an object by casting that object as a unsigned char pointer. If the operation fails, setstate(badbit) is called.
A reference to ostream. The this pointer is returned.
#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