美文网首页
C++使用boost智能指针封装C文件函数

C++使用boost智能指针封装C文件函数

作者: FredricZhu | 来源:发表于2020-11-04 12:34 被阅读0次

文件结构


图片.png

main.cpp

#include "utils/utils.hpp"

int main()
{
    FilePtr ptr = FileOpen("1.log", "r");
    std::string s;
    int n;
    while ((n = FileRead(ptr, s, BUFFER_SIZE)) != EOF)
    {
        std::cout << s;
    }
    std::cout << std::endl;

    system("pause");
    return 0;
}

utils.hpp

#ifndef UTILS_HPP
#define UTILS_HPP
#include <windows.h>
#include <iostream>
#include <boost/shared_ptr.hpp>
#include <boost/format.hpp>
using namespace boost;
using namespace std;

#define EOF 0
#define BUFFER_SIZE 50

typedef boost::shared_ptr<FILE> FilePtr;  

void FileClose(FILE *file) {
    int result = fclose(file);
    std::cout << "invoke file close, result = " << result <<std::endl;
}

FilePtr FileOpen(std::string path, std::string mode) {
    FilePtr fptr(fopen(path.c_str(), mode.c_str()), FileClose);
    return fptr;
}

int FileRead(FilePtr& f, std::string& s, size_t size) {
    char data[size+1];
    int res =  fread(data, 1, size, f.get());
    data[size] = '\0';
    s = boost::str(boost::format(data));
    return res;
}
#endif

程序输出如下
最后一句关闭是精华

图片.png

相关文章

  • C++使用boost智能指针封装C文件函数

    文件结构 main.cpp utils.hpp 程序输出如下最后一句关闭是精华

  • 智能指针

    指针的危害 指针未初始化 野指针 内存泄漏 参考阅读C/C++指针使用常见的坑 智能指针分类 本质:将指针封装为类...

  • 窥见C++11智能指针

    导语: C++指针的内存管理相信是大部分C++入门程序员的梦魇,受到Boost的启发,C++11标准推出了智能指针...

  • 第十五章:源文件与程序

    C头文件实现C++头文件方式 函数指针image.png 头文件的使用image.pngimage.pngimag...

  • C++知识点

    C++基本方法: C++ memcpy C++基本特性: C++引用(vs指针) C++指针 C++封装: 将...

  • 技能

    C++ C++特性 C++11 多态和继承 构造函数 析构函数 手写代码实现string类 手写代码实现智能指针 ...

  • c++ 指针

    原文地址摘要:这篇文章详细介绍C/C++的函数指针,请先看以下几个主题:使用函数指针定义新的类型、使用函数指针作为...

  • C++和Java解决智能指针或对象循环引用的策略

    https://zwmf.iteye.com/blog/1738574 C++ Java 在C++中使用过智能指针...

  • C++和Python的混合编程-Boost::python的编译

    视频教程:boost::python库的编译和使用的基本方法 boost::python用于将C++的函数和对象导...

  • Qt/C/C++推荐代码规范

    Qt/C/C++工程推荐使用下面代码规范: 代码采用C/C++11标准,尽量使用智能指针,尽量不使用裸指针(QT中...

网友评论

      本文标题:C++使用boost智能指针封装C文件函数

      本文链接:https://www.haomeiwen.com/subject/yncgvktx.html