Advertisement
RobertDeMilo

BB4.12 Идея RAII

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