Advertisement
intsashka

mz06-3

Apr 27th, 2018
93
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.73 KB | None | 0 0
  1. #include <cstdio>
  2.  
  3. class FileWrapper {
  4.     struct FileCount {
  5.         FILE *fd = nullptr;
  6.         unsigned int count = 0;
  7.  
  8.         FileCount(FILE *pfd) : fd(pfd), count(1) {}
  9.     };
  10.  
  11.     FileCount *fileCount = nullptr;
  12.  
  13.     void setFileCount(FileCount *newFileCount) {
  14.         if (fileCount != nullptr) {
  15.             --(fileCount->count);
  16.             if (fileCount->count == 0) {
  17.                 fclose(fileCount->fd);
  18.                 delete fileCount;
  19.             }
  20.         }
  21.  
  22.         fileCount = newFileCount;
  23.         if (fileCount != nullptr) {
  24.             ++(fileCount->count);
  25.         }
  26.     }
  27.  
  28.     void swap(FileWrapper& other) noexcept {
  29.         FileCount* tmp = other.fileCount;
  30.         other.fileCount = fileCount;
  31.         fileCount = tmp;
  32.     }
  33. public:
  34.     FileWrapper(const char *path) {
  35.         FILE *fd = fopen(path, "w");
  36.         fileCount = new FileCount(fd);
  37.     }
  38.  
  39.     FileWrapper(const FileWrapper &fileWrapper) : fileCount(fileWrapper.fileCount) {
  40.         ++(fileCount->count);
  41.     }
  42.  
  43.     FileWrapper(const FileWrapper &&fileWrapper) : fileCount(fileWrapper.fileCount) {
  44.         ++(fileCount->count);
  45.     }
  46.  
  47.     FileWrapper& operator=(const FileWrapper &fileWrapper) {
  48.         if (this == &fileWrapper) {
  49.             return *this;
  50.         }
  51.         FileWrapper(fileWrapper).swap(*this);
  52.         return *this;
  53.     }
  54.  
  55.     FileWrapper& operator=(const FileWrapper &&fileWrapper) {
  56.         if (this == &fileWrapper) {
  57.             return *this;
  58.         }
  59.         FileWrapper(fileWrapper).swap(*this);
  60.         return *this;
  61.     }
  62.  
  63.     FileWrapper& operator<<(char ch) {
  64.         fputc(ch, fileCount->fd);
  65.         return *this;
  66.     }
  67.  
  68.     ~FileWrapper() {
  69.         setFileCount(nullptr);
  70.     }
  71. };
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement