home *** CD-ROM | disk | FTP | other *** search
/ OS/2 Shareware BBS: 10 Tools / 10-Tools.zip / IDIOMS.ZIP / 3-3.C < prev    next >
C/C++ Source or Header  |  1991-12-04  |  1KB  |  50 lines

  1. /* Copyright (c) 1992 by AT&T Bell Laboratories. */
  2. /* Advanced C++ Programming Styles and Idioms */
  3. /* James O. Coplien */
  4. /* All rights reserved. */
  5.  
  6. #include <iostream.h>
  7. #include <fcntl.h>
  8. #include <osfcn.h>
  9.  
  10. class FileRef {
  11. private:
  12.     class File &f;
  13.     char buf[1];
  14.     unsigned long ix;
  15. public:
  16.     FileRef (File &ff, unsigned long i) : f (ff), ix (i) { }
  17.     FileRef &operator=(char c);
  18.     operator char ();
  19. };
  20.  
  21. class File {
  22. friend class FileRef;
  23. public:
  24.     File(const char *name) {
  25.         fd = open(name, O_RDWR|O_CREAT, 0664);
  26.     }
  27.     ~File() { close(fd); }
  28.     FileRef operator[] (unsigned long ix) {
  29.         return FileRef(*this, ix);
  30.     }
  31. private:
  32.     int fd;
  33. };
  34.  
  35. FileRef& FileRef::operator=(char c) {
  36.     lseek(f.fd, ix, 0); write(f.fd, &c, 1); return *this;
  37. }
  38.  
  39. FileRef::operator char () {
  40.     lseek(f.fd, ix, 0); read(f.fd, buf, 1); return buf[0];
  41. }
  42.  
  43. int main() {
  44.     File foo("foo");
  45.     foo[5] = '5';
  46.     foo[10] = 'l';
  47.     char c = foo[5];
  48.     cout << "c = " << c << endl;
  49. }
  50.