FileUtil用来操作文件。AppendFile用来写日志,使用的fopen函数;ReadSmallFile使用open函数用来读取linux内核的一些信息。

FileUtil.h

// Use of this source code is governed by a BSD-style license
// that can be found in the License file.// Author: Shuo Chen (chenshuo at chenshuo dot com)
//
// This is a public header file, it must only include public header files.#ifndef MUDUO_BASE_FILEUTIL_H
#define MUDUO_BASE_FILEUTIL_H#include "muduo/base/noncopyable.h"
#include "muduo/base/StringPiece.h"
#include <sys/types.h>  // for off_tnamespace muduo
{
namespace FileUtil
{// read small file < 64KB
class ReadSmallFile : noncopyable//小文件读取
{public:ReadSmallFile(StringArg filename);~ReadSmallFile();// return errnotemplate<typename String>  //函数模板int readToString(int maxSize,                  //最大的长度String* content,             //读入content缓冲区int64_t* fileSize,            //文件大小int64_t* modifyTime,          //修改时间int64_t* createTime);     //创建时间/// Read at maxium kBufferSize into buf_// return errnoint readToBuffer(int* size);const char* buffer() const { return buf_; }static const int kBufferSize = 64*1024;//64Kprivate:int fd_;int err_;char buf_[kBufferSize];
};// read the file content, returns errno if error happens.
template<typename String>   //函数模板
int readFile(StringArg filename,            //读取文件,是对ReadSmallFile的一个包装int maxSize,String* content,int64_t* fileSize = NULL,int64_t* modifyTime = NULL,int64_t* createTime = NULL)
{ReadSmallFile file(filename);return file.readToString(maxSize, content, fileSize, modifyTime, createTime);
}// not thread safe
class AppendFile : noncopyable
{public:explicit AppendFile(StringArg filename);~AppendFile();void append(const char* logline, size_t len);void flush();off_t writtenBytes() const { return writtenBytes_; }private:size_t write(const char* logline, size_t len);FILE* fp_;char buffer_[64*1024];//64Koff_t writtenBytes_;
};}  // namespace FileUtil
}  // namespace muduo#endif  // MUDUO_BASE_FILEUTIL_H

FileUtil.cc

// Use of this source code is governed by a BSD-style license
// that can be found in the License file.
//
// Author: Shuo Chen (chenshuo at chenshuo dot com)#include "muduo/base/FileUtil.h"
#include "muduo/base/Logging.h"#include <assert.h>
#include <errno.h>
#include <fcntl.h>
#include <stdio.h>
#include <sys/stat.h>
#include <unistd.h>using namespace muduo;FileUtil::AppendFile::AppendFile(StringArg filename): fp_(::fopen(filename.c_str(), "ae")),  // 'e' for O_CLOEXEC        //这里用了fopenwrittenBytes_(0)
{assert(fp_);::setbuffer(fp_, buffer_, sizeof buffer_);     //设置缓冲区// posix_fadvise POSIX_FADV_DONTNEED ?
}FileUtil::AppendFile::~AppendFile()
{::fclose(fp_);
}void FileUtil::AppendFile::append(const char* logline, const size_t len)
{size_t n = write(logline, len);//将日志写入文件中size_t remain = len - n;while (remain > 0){size_t x = write(logline + n, remain);if (x == 0){int err = ferror(fp_);if (err){fprintf(stderr, "AppendFile::append() failed %s\n", strerror_tl(err));}break;}n += x;remain = len - n; // remain -= x}writtenBytes_ += len;
}void FileUtil::AppendFile::flush()         //立刻刷新
{::fflush(fp_);
}size_t FileUtil::AppendFile::write(const char* logline, size_t len)
{// #undef fwrite_unlockedreturn ::fwrite_unlocked(logline, 1, len, fp_);
}//fopen有缓冲,open是没有缓冲FileUtil::ReadSmallFile::ReadSmallFile(StringArg filename): fd_(::open(filename.c_str(), O_RDONLY | O_CLOEXEC)),        //构造函数打开文件err_(0)
{buf_[0] = '\0';if (fd_ < 0){err_ = errno;}
}FileUtil::ReadSmallFile::~ReadSmallFile()
{if (fd_ >= 0)      //文件描述符有效则关闭{::close(fd_); // FIXME: check EINTR}
}// return errno
template<typename String>
int FileUtil::ReadSmallFile::readToString(int maxSize,              //将文件读到contentString* content,int64_t* fileSize,int64_t* modifyTime,int64_t* createTime)
{static_assert(sizeof(off_t) == 8, "_FILE_OFFSET_BITS = 64");assert(content != NULL);int err = err_;if (fd_ >= 0){content->clear();if (fileSize){struct stat statbuf;//fstat函数用来 获取文件(普通文件,目录,管道,socket,字符,块()的属性//fstat 通过文件描述符获取文件对应的属性if (::fstat(fd_, &statbuf) == 0)//fstat用来获取文件大小,保存到缓冲区当中{if (S_ISREG(statbuf.st_mode)){*fileSize = statbuf.st_size;//stat结构体中有st_size参数就是文件大小,串给输入参数指针content->reserve(static_cast<int>(std::min(implicit_cast<int64_t>(maxSize), *fileSize)));}else if (S_ISDIR(statbuf.st_mode))//S_ISDIR功能是判断一个路径是否为目录{err = EISDIR;}if (modifyTime){*modifyTime = statbuf.st_mtime;}if (createTime){*createTime = statbuf.st_ctime;}}else{err = errno;}}while (content->size() < implicit_cast<size_t>(maxSize)){size_t toRead = std::min(implicit_cast<size_t>(maxSize) - content->size(), sizeof(buf_));ssize_t n = ::read(fd_, buf_, toRead);//从文件当中读取数据到字符串if (n > 0){content->append(buf_, n); //追加到字符串}else{if (n < 0){err = errno;}break;}}}return err;
}int FileUtil::ReadSmallFile::readToBuffer(int* size)
{int err = err_;if (fd_ >= 0){ssize_t n = ::pread(fd_, buf_, sizeof(buf_)-1, 0);if (n >= 0){if (size){*size = static_cast<int>(n);//static_cast强制类型转换}buf_[n] = '\0';}else{err = errno;}}return err;
}//对成员函数进行模板的显示实例化,提高效率
template int FileUtil::readFile(StringArg filename,int maxSize,string* content,int64_t*, int64_t*, int64_t*);template int FileUtil::ReadSmallFile::readToString(int maxSize,string* content,int64_t*, int64_t*, int64_t*);

muduo之FileUtil相关推荐

  1. muduo之LogFile

    muduo之LogFile,LogFile是控制日志怎么和文件打交道,其中包含常用的对日志处理的一些操作.AsyncLogging异步日志需要调用LogFile的接口将日志写入文件,其中包含了Appe ...

  2. muduo:获取进程相关信息

    muduo里面有专门获取进程信息的类,记录一下. // Use of this source code is governed by a BSD-style license // that can b ...

  3. 客户端压测server端计算qps以及不同延迟时间下响应数量所占百分比

    将时间戳转为时间显示 date -d @978278400 percentile.h https://github.com/chenshuo/muduo/blob/master/examples/su ...

  4. muduo 与 boost asio 吞吐量对比

    muduo (http://code.google.com/p/muduo) 是一个基于 Reactor 模式的 C++ 网络库,我在编写它的时候并没有以高并发高吞吐为主要目标,但出乎我的意料,pin ...

  5. muduo之Logger

    Logger用来记录和分析日志. Logging.h // Use of this source code is governed by a BSD-style license // that can ...

  6. muduo之Atomic

    Atomic是muduo原子操作的实现类. Atomic.h // Use of this source code is governed by a BSD-style license // that ...

  7. muduo之Singleton

    muduo中的单例模式 Singleton.h // Use of this source code is governed by a BSD-style license // that can be ...

  8. muduo之CountDownLatch.cc

    CountDownLatch用线程同步的. CountDownLatch.h // Use of this source code is governed by a BSD-style license ...

  9. muduo之ThreadPool

    muduo中的线程池. ThreadPool.h // Use of this source code is governed by a BSD-style license // that can b ...

最新文章

  1. directx 双缓冲 运动 闪烁_24期0利率 | BMW超值福袋开启“双11”购车狂欢节!!
  2. 目录文件和根目录文件夹
  3. 2010年8月blog汇总:敏捷个人和OpenExpressApp之建模支持
  4. C++ Primer 5th笔记(chap 18 大型程序工具) 重载与命名空间
  5. 桌面支持--打印机任务取消不了
  6. Appium同时运行多个设备
  7. 递归神经网络变形之 (Long Short Term Memory,LSTM)
  8. WPF的WebBrowser屏蔽弹出脚本错误窗口
  9. Netbean6.1中svn配置
  10. 超简单的Spring入门案例制作,快来看看吧!
  11. word背景颜色怎么设置绿色?把word背景调成绿色
  12. Python制作安卓游戏外挂
  13. android 1g运行内存,全新安卓系统首曝光:安卓9.0只要1G运存就能流畅运行
  14. 异度装甲解惑(转载)
  15. 东方通TongWeb前后端应用部署
  16. 史上最全的Android面试题集锦,大厂内部资料
  17. neo4j桌面版安装
  18. linux获取完整的man(manpages)linux参考手册/中文man的下载和使用/获取buildin 命令的完整帮助文档/多种man手册/man着色colorful man
  19. ffmpeg 命令行 pcm 编码 MP3
  20. mysql安装mysql-5.7.35-1.el7.x86_64.rpm-bundle.tar,问题及其他ip访问mysql

热门文章

  1. Windows下RabbitMQ安装,部署,配置
  2. alert和console的区别
  3. iOS 改变UILabel部分颜色
  4. iOS开发——你真的会用SDWebImage?
  5. C#程序员干货系列之语音识别
  6. ROS Gazebo(二):概述
  7. 字符驱动之按键(一:无脑轮询法)
  8. 新CCIE笔记之'口口相传'路由协议
  9. WEB中会话跟踪[转]
  10. 关于SWT开发的一个坑——Invalid thread access