Advertisement
RobertDeMilo

BB4.13 RAII обертка над файлом

Jun 21st, 2024
85
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.36 KB | None | 0 0
  1. #include <cstdio>
  2. #include <iostream>
  3.  
  4. using namespace std;
  5.  
  6. class File
  7. {
  8. private:
  9.     FILE* f;
  10.     File(const File&) = delete;
  11.     void operator=(const File&) = delete;
  12.  
  13. public:
  14.     File(const string& filename)
  15.     {
  16.         f = fopen(filename.c_str(), "w");
  17.         if (f == nullptr)
  18.         {
  19.             throw runtime_error("cannot_open "+filename);
  20.         }
  21.     }
  22.  
  23.     void Write(const string& line)
  24.     {
  25.         fputs(line.c_str(), f);
  26.     }
  27.     ~File()
  28.     {
  29.         fclose(f);
  30.     }
  31.  
  32. };
  33.  
  34. int main()
  35. {
  36.     //// открываем файл и получаем его дескриптор
  37.     //FILE* f = fopen("output.txt", "w");
  38.     //// если не nullptr, то файл успешно открыт
  39.     //if (f != nullptr)
  40.     //{
  41.     //  //fprintf(f, "Hello, world!\n");
  42.     //  fputs("Hello, world!\n", f);
  43.     //  fputs("This file is written with fputs!\n", f);
  44.     //  //...
  45.     //  fclose(f);//закрываем файл
  46.     //}
  47.     //else
  48.     //{
  49.     //  printf("Ошибка при открытии файла!\n");
  50.     //}
  51.     try
  52.     {
  53.         File f("output.txt");
  54.         File f2 = f;
  55.         f.Write("Hello, world!\n");
  56.         f.Write("This is RAII file!\n");
  57.     }
  58.     catch (...)
  59.     {
  60.         printf("Ошибка при открытии файла!\n");
  61.     }
  62.    
  63.     return 0;
  64. }
  65. Advertisement
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement