先介绍关于获取文件信息的函数:
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
//获取path路径的文件信息
int stat(const char *path, struct stat *buf);
//获取文件描述符fields的文件信息
int fstat(int filedes, struct stat *buf);
//类似于stat函数,但当参数1是符号链接时,返回该符号链接的信息,而不是该链接引用的文件信息
int lstat(const char *path, struct stat *buf);
三个函数功能是一致的,但应用于不同文件对象。
关于第二个参数struct stat:
struct stat{
mode_t st_mode; //(文件保护模式)文件类型和权限信息 结构体详解请参考此处
ino_t st_ino; //文件结点号
dev_t st_dev; //文件所在设备的文件系统标识号 device number (file system)
dev_t st_rdev; //文件所表示的特殊设备文件的设备标识 device number for special files
nlink_t st_nlink; //符号链接数
uid_t st_uid; //文件用户标识 用户ID
gid_t st_gid; //文件用户组标识 组ID
off_t st_size; // 总大小,字节为单位 size in bytes,for regular files
time_t st_st_atime; //文件内容最后访问的时间
time_t st_mtime; //文件内容最后修改时间
time_t st_ctime; //文件结构最后状态改变时间
blksize_t st_blksize; // 文件系统的最优I/O块大小 best I/O block size
blkcnt_t st_blocks; //分配给文件的块的数量,512字节为1单元 number of disk blocks allocated
};
其中st_mode用以下的宏来判断文件类型:
S_ISREG(st_mode)//是否是一个常规文件.
S_ISDIR(st_mode)//是否是一个目录
S_ISLNK(st_mode)//是否是一个连接.
S_ISCHR(st_mode)//是否是一个字符设备.
S_ISBLK(st_mode)//是否是一个块设备
S_ISFIFO(st_mode)//是否 是一个FIFO文件.
S_ISSOCK(st_mode)//是否是一个SOCKET文件
下面是muduo库FileUtil.h和FileUtil.cc
//FileUtil.h
#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_t
namespace muduo
{
namespace FileUtil
{
// read small file < 64KB
class ReadSmallFile : noncopyable //用来读取linux内核的一些信息
{
public:
ReadSmallFile(StringArg filename);
~ReadSmallFile();
// return errno
template<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 errno