The class constructor and destructor semantics can be used to provide safe files. C++ semantics guarantee that once the constructor for a variable completes (such as for local file on Line [15] below) any control transfer out of the variable's scope will cause a call to its destructor. This is used in the following code to close the file; thus, the file use is safe as the function properly releases acquired resources.
[ 1] #include "stdio.h"
[ 2] class SafeFile
[ 3] {
[ 4] private:
[ 5] FILE *f;
[ 6]
[ 7] public:
[ 8] SafeFile(const char *name, const char *mode)
{f = fopen(name, mode);}
[ 9] ~SafeFile() {fclose (f);}
[10] operator FILE*() {return f;}
[11] };
[12]
[13] f(char *buf, int size)
[14] {
[15] SafeFile file("data", "r");
[16]
[17] if (fread(buf, 1, size, file) != size)
[18] return(-1);
[19] ...
[20] fclose(file);
[21] }