[其它产品/技术] 文件操作中的RAII使用

[复制链接]
916|7
 楼主| 小小蚂蚁举千斤 发表于 2024-3-26 13:50 | 显示全部楼层 |阅读模式
本帖最后由 小小蚂蚁举千斤 于 2024-3-28 19:28 编辑

在文件操作中,使用RAII可以有效地管理文件资源的获取和释放,避免忘记关闭文件或异常时未能正确释放资源的问题。



  1. #include <iostream>
  2. #include <fstream>

  3. class File {
  4. public:
  5.     File(const std::string& filename) : file(filename) {
  6.         if (!file.is_open()) {
  7.             throw std::runtime_error("Failed to open file: " + filename);
  8.         }
  9.     }

  10.     ~File() {
  11.         if (file.is_open()) {
  12.             file.close();
  13.         }
  14.     }

  15.     void write(const std::string& data) {
  16.         file << data;
  17.     }

  18. private:
  19.     std::ofstream file;
  20. };

  21. int main() {
  22.     try {
  23.         File myfile("example.txt");
  24.         myfile.write("Hello, RAII!");
  25.     } catch (const std::exception& e) {
  26.         std::cout << e.what() << std::endl;
  27.     }

  28.     return 0;
  29. }



LOVEEVER 发表于 2024-3-27 14:37 | 显示全部楼层
使用RAII可以有效地管理文件资源的获取和释放,楼主这个程序再规范一下就更好
jf101 发表于 2024-3-28 19:04 | 显示全部楼层
很好的解决了忘记关闭文件或异常时未能正确释放资源的问题
星辰大海不退缩 发表于 2024-3-29 14:19 | 显示全部楼层
RAII可以有效地管理文件资源的获取和释放,避免忘记关闭文件或异常时未能正确释放资源的问题。
suncat0504 发表于 2024-4-30 17:46 | 显示全部楼层
学习了!谢谢分享!这硬件的开发,和软件开发靠的越来越近了。
和下土 发表于 2024-6-30 16:51 | 显示全部楼层
在文件操作中,RAII(Resource Acquisition Is Initialization)是一种重要的资源管理技术,特别是在C++等支持对象生命周期管理的语言中
和下土 发表于 2024-6-30 16:51 | 显示全部楼层
RAII 的核心思想是利用对象的生命周期来管理资源的获取和释放,确保资源在对象生命周期结束时被正确释放,从而避免资源泄露和错误处理问题。
和下土 发表于 2024-6-30 16:51 | 显示全部楼层
#include <fstream>
#include <stdexcept>

class FileRAII {
public:
    FileRAII(const std::string& filename) : file(filename) {
        if (!file.is_open()) {
            throw std::runtime_error("Failed to open file");
        }
    }

    ~FileRAII() {
        if (file.is_open()) {
            file.close();
        }
    }

    // Add methods to read/write to the file as needed

private:
    std::ifstream file; // Example using ifstream, can be ofstream or fstream
};

您需要登录后才可以回帖 登录 | 注册

本版积分规则

228

主题

2630

帖子

1

粉丝
快速回复 在线客服 返回列表 返回顶部