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

2020-11-04  本文已影响0人  FredricZhu

文件结构


图片.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
上一篇 下一篇

猜你喜欢

热点阅读