文件结构
图片.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
程序输出如下
最后一句关闭是精华
网友评论