home *** CD-ROM | disk | FTP | other *** search
/ The C Users' Group Library 1994 August / wc-cdrom-cusersgrouplibrary-1994-08.iso / listings / v_09_12 / 9n12105a < prev    next >
Text File  |  1991-04-15  |  2KB  |  63 lines

  1. //  Listing 4 - Functions to open and close files 
  2. //  (See Listing 3 for the class definition)
  3.  
  4. //  =============================================
  5. //  Function to open a file for class binaryfile
  6. //
  7. int binaryfile::fileopen (const char *n, enum FILEMODE m,
  8.         long h, enum SHAREMODE s) {
  9.     if (isopen() || !*n || record == NULL) return -2;  // Error
  10.  
  11. //  The O_type and S_type flags are defined in <sys\stat.h>
  12. //  The SH_type flags are Turbo C sharing flags from <share.h>
  13.     unsigned access = O_BINARY |
  14.         (m == Readonly ? O_RDONLY : O_RDWR) |   // read/write access
  15.         (s == WriteShared ? SH_DENYNONE :       // file sharing
  16.            (s == ReadShared ? SH_DENYWR : SH_DENYRW)); 
  17.     if (m == Append || m == Recreate) access |= O_APPEND;
  18.  
  19.     handle = (m != Recreate ? open (n, access) :
  20.         open (n, access | O_CREAT | O_TRUNC, S_IREAD | S_IWRITE));
  21.     if (handle < 0) return handle;   // trap error
  22.  
  23. // set values into elements in the object
  24.     mode = m;
  25.     header = h;
  26.     recnbr = locked = 0L;
  27.     strncpy (name, n, 80); name[80] = '\0';
  28.     share = s;
  29.     countrecords();
  30.     return 0;   // successful open
  31. }
  32.  
  33. //  =============================================
  34. //  Function to close a file for class binaryfile
  35. //
  36. int binaryfile::fileclose () {
  37.     int ret;
  38.     if (!isopen()) return 0;   // already closed
  39.     if (locked > 0L) unlockrecord();
  40.     if ((ret = close (handle)) == 0) handle = -1;
  41.     return ret;
  42. }
  43.  
  44. //  =============================================
  45. //  Function to change the record length in
  46. //     class binaryfile
  47. //
  48. int binaryfile::changelength (unsigned len) {
  49.     void *ptr;
  50.     if (isopen() || !len || len > 4096) return -2; // Error
  51.     if ((ptr = realloc (record, len)) == NULL) return -1;
  52.     record = (char*) ptr; length = len;
  53.     return 0;
  54. }
  55.  
  56. //  =============================================
  57. //  Function to count the records in class binaryfile
  58. //
  59. long binaryfile::countrecords() {  
  60.     return (count = (lseek (handle, 0, SEEK_END) - header) / length);
  61. };
  62.  
  63.