#include <iostream>
#include <fstream>

using namespace std;

void ifstream_test();
void ofstream_test();
void ifstream_test2();

int main() {
  cout << "testing: opening two input files with the same ifstream: ";
  ifstream_test();
  
  cout << "testing: opening everything with ofstreams: ";
  ofstream_test();  

  cout << "testing: opening file that's been written with same ifstream: ";
  ifstream_test2();
  
  return 0; 
}

void ifstream_test() {
  ifstream one;
  
  one.open("test.dat");
  if(one.fail()) {
    cout << "first failed" << endl;
    exit(1);
  }
  one.close();
  one.open("othertest.dat");
  if(one.fail()) {
    cout << "second failed" << endl;
    exit(1);
  }
  one.close();
  one.open("test.dat");
  if(one.fail()) {
    cout << "third failed" << endl;
    exit(1);
  }
  one.close();
  cout << "All cool" << endl;
}

void ofstream_test() {
  ofstream out;
  ifstream in;
  
  out.open("results.dat");
  if(out.fail()) {
    cout << "first out open failed" << endl;
    exit(1);
  }
  out.close();
  in.open("test.dat");
  if(in.fail()) {
    cout << "blah.  this should not fail" << endl;
    exit(1);
  }
  string blah;
  in >> blah;
  in.close();
  out.open("test.dat");
  if(out.fail()) {
    cout << "second out open failed" << endl;
    exit(1);
  }
  out.close();
  out.open("results.dat");
  if(out.fail()) {
    cout << "third out open failed" << endl;
    exit(1);
  }
  out.close();
  cout << "All cool" << endl;
}

void ifstream_test2() {
  ofstream out;
  ifstream in;

  in.open("test.dat");
  if(in.fail())
    exit(1);
  out.open("results.dat");
  if(out.fail())
    exit(1);
  string blah;
  in >> blah;  //line 1
  //out << blah << "I have written in this file" << endl; //line 2
  in.close();
  out.close();
  in.open("results.dat");
  if(in.fail()) {
    cout <<"Here's where it fails" << endl; // but only if lines 1 and 2 or just line one is there.  Wtf?
    exit(1);
  }
  out.open("test.dat");
  if(out.fail())
    cout << "blah" << endl;
  out.close();

  cout << "all cool" << endl;
}
