//  Listing 3 - Header file for binaryfile class 
//  This contains the full class definition with
//     the constructor and destructor functions
//

enum FILEMODE  {Readonly, Update, AnyWrite, Append, Recreate};
enum READMODE  {FirstRecord, NextRecord, PreviousRecord, LastRecord};
enum SHAREMODE {NoneShared, ReadShared, WriteShared};

class binaryfile {
private:
    char name[81];	  // name of file  (size is DOS specific)
    enum FILEMODE mode;   // access mode of the file
    enum SHAREMODE share; // whether shared access is allowed
    unsigned length;      // record length
    int      handle;      // file handle  (-1 if not open)
    long     header;      // size of header at start of file
    long     count;       // number of records in the file
    long     recnbr;      // current record number (starting at 1)
    long     locked;      // if >0, currently locked record
    long     countrecords();  // check size of file
public:
    char     *record;    // pointer to record area
    binaryfile (unsigned);  // constructor 
    ~binaryfile ();   	    // destructor
    // inline functions to read private elements
    long     getcount  ()      {
        return (share == WriteShared ? countrecords() : count);
    };
    long     getheader ()      {return header;};
    unsigned getlength ()      {return length;};
    long     getlocked ()      {return locked;};
    enum FILEMODE getmode ()   {return mode;};
    char*    getname (char *n) {return (strcpy (n, name));};
    long     getrecnbr ()      {return recnbr;};
    enum SHAREMODE getshare()  {return share;};
    int      isopen ()         {return (handle >= 0);};
    // Functions to open, close, read, write
    int  changelength (unsigned); // change record length
    int  fileopen  (const char *, enum FILEMODE = Readonly,
         long = 0L, enum SHAREMODE = ReadShared);// Open file
    int  fileclose ();       // close the file
    int  fileread  (enum READMODE = NextRecord); // read sequentially
    int  fileread  (long);   // read a specific record
    int  filewrite ();       // rewrite record, or append
    int  filewrite (long);   // write a specific record
    int  lockrecord (long);  // lock a specific record
    void unlockrecord ();    // unlock current record
};

//  =============================================
//  The constructor for class binaryfile
//
binaryfile::binaryfile (unsigned len) {
    length = len;  // Assign the record length
    handle = -1;
    record = (len <= 4096 ? (char*) malloc (len + 2) : NULL);
        // assign record space with safety zone
}

//  =============================================
//  The destructor for class binaryfile
//
binaryfile::~binaryfile  () {
    if (isopen()) fileclose();  // close the file if open
    if (record != NULL) free (record);  // release area
}

