// RAII 
#include <iostream>
#include <stdio.h>
#include <stdexcept>

using namespace std;

void f();

// use an object to represent a resource
class File_handle { // belongs in some support library
    FILE* p;
public:
	File_handle(const char* pp, const char* r) {
		p = fopen(pp,r);
		// Commented out for running on Ideone.com
        // if (p==0) throw std::runtime_error("File_error{pp,r}");
	}
    
	File_handle(const string& s, const char* r) {
        p = fopen(s.c_str(),r);
        // Commented out for running on Ideone.com
        //if (p==0) throw std::runtime_error("File_error{s,r}");
	}
    
	~File_handle() {
        cout << "fclose() called in File_handle" << endl;
		fclose(p);
	} // destructor
	// copy operations
	// access functions
};

struct A
{
    ~A() {
        cout << "~A() called" << endl;
    };
};

void good (string s) {
    File_handle fh (s, "r");
    // use fh
    f(); // OOPS!
}

void bad(const char* p)
{
    FILE* fh = fopen(p,"r"); // acquire
	// use f
	f(); // OOPS!
	fclose(fh); // release
    cout << "fclose() called" << endl;
}

void f()
{
	A a;
	throw 42;
}

int main() {

	try
	{
        // Try either of these
		//f();
		//bad("c:\\temp\\1.txt");
        //good("c:\\temp\\1.txt");
	}
	catch ( ... ) {}
	
	return 0;
}