Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <cstdio>
- class FileWrapper {
- struct FileCount {
- FILE *fd = nullptr;
- unsigned int count = 0;
- FileCount(FILE *pfd) : fd(pfd), count(1) {}
- };
- FileCount *fileCount = nullptr;
- void setFileCount(FileCount *newFileCount) {
- if (fileCount != nullptr) {
- --(fileCount->count);
- if (fileCount->count == 0) {
- fclose(fileCount->fd);
- delete fileCount;
- }
- }
- fileCount = newFileCount;
- if (fileCount != nullptr) {
- ++(fileCount->count);
- }
- }
- void swap(FileWrapper& other) noexcept {
- FileCount* tmp = other.fileCount;
- other.fileCount = fileCount;
- fileCount = tmp;
- }
- public:
- FileWrapper(const char *path) {
- FILE *fd = fopen(path, "w");
- fileCount = new FileCount(fd);
- }
- FileWrapper(const FileWrapper &fileWrapper) : fileCount(fileWrapper.fileCount) {
- ++(fileCount->count);
- }
- FileWrapper(const FileWrapper &&fileWrapper) : fileCount(fileWrapper.fileCount) {
- ++(fileCount->count);
- }
- FileWrapper& operator=(const FileWrapper &fileWrapper) {
- if (this == &fileWrapper) {
- return *this;
- }
- FileWrapper(fileWrapper).swap(*this);
- return *this;
- }
- FileWrapper& operator=(const FileWrapper &&fileWrapper) {
- if (this == &fileWrapper) {
- return *this;
- }
- FileWrapper(fileWrapper).swap(*this);
- return *this;
- }
- FileWrapper& operator<<(char ch) {
- fputc(ch, fileCount->fd);
- return *this;
- }
- ~FileWrapper() {
- setFileCount(nullptr);
- }
- };
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement