C++/File/Exception Error

Материал из C\C++ эксперт
Перейти к: навигация, поиск

Use exceptions to watch for and handle I/O errors.

  
#include <iostream>
#include <fstream>
#include <cstring>
using namespace std;
struct inventory {
  char item[20];
  int quantity;
  double cost;
};
int main()
{
  int completion_status = 0;
  ofstream fout;
  fout.exceptions(ios::failbit | ios::badbit);
  try {
    fout.open("InvDat.dat", ios::out | ios::binary);
  } catch(ios_base::failure exc) {
    cout << "Cannot open file.\n";
    cout << "String returned by what(): " << exc.what() << endl;
    return 1;
  }
  inventory inv[3];
  strcpy(inv[0].item,"A");
  inv[0].quantity = 1;
  inv[0].cost = 9.9;
  strcpy(inv[1].item, "B");
  inv[1].quantity = 2;
  inv[1].cost = 7.5;
  strcpy(inv[2].item, "C");
  inv[2].quantity = 19;
  inv[2].cost = 2.75;
  try {
    for(int i=0; i<3; i++)
      fout.write((const char *) &inv[i], sizeof(inventory));
  } catch(ios_base::failure exc) {
    cout << exc.what() << endl;
    completion_status = 1;
  }
  try {
    fout.close();
  } catch(ios_base::failure exc) {
    cout << exc.what() << endl;
    completion_status = 1;
  }
  return completion_status;
}