Save and read structure : ofstream « File Stream « C++ Tutorial






#include <iostream>
#include <fstream>
#include <cstring>
using namespace std;

struct MyRecord {
  char name[80];
  double balance;
  unsigned long account_num;
};

int main()
{
  struct MyRecord acc;

  strcpy(acc.name, "R");
  acc.balance = 1.3;
  acc.account_num = 34;

  ofstream outbal("balance", ios::out | ios::binary);
  if(!outbal) {
    cout << "Cannot open file.\n";
    return 1;
  }

  outbal.write((char *) &acc, sizeof(struct MyRecord));
  outbal.close();

  ifstream inbal("balance", ios::in | ios::binary);
  if(!inbal) {
    cout << "Cannot open file.\n";
    return 1;
  }

  inbal.read((char *) &acc, sizeof(struct MyRecord));

  cout << acc.name << endl;
  cout << "Account # " << acc.account_num;
  cout.precision(2);
  cout.setf(ios::fixed);
  cout << endl << "Balance: $" << acc.balance;

  inbal.close();
  return 0;
}
R
Account # 34
Balance: $1.30"








12.10.ofstream
12.10.1.Save char array to a file
12.10.2.Read char array from a file
12.10.3.Writing on a text file
12.10.4.Writing numbers to a file
12.10.5.ofstream: seek from beginning
12.10.6.Save and read double array in a binary file
12.10.7.Save and read structure
12.10.8.Save chars to a binary file
12.10.9.Demonstrate peek(), unget(), and ignore().
12.10.10.Create a sequential file.