Linux下C++文件判断方式
前言
开发webserver中涉及到其中的读取文件,做一个静态webserver常常需要都文件,比如HTML文件、CSS文件、图片资源等。竟然用过就当在记录整理一下。
详细说明
主要涉及到stat()
函数、struct stat
结构体、S_ISDIR
宏及S_ISREG
宏。
stat结构体
经常用到st_mode、st_size两个属性。struct stat { dev_t st_dev; /* [XSI] ID of device containing file */ ino_t st_ino; /* [XSI] File serial number */ mode_t st_mode; /* [XSI] Mode of file (see below) */ nlink_t st_nlink; /* [XSI] Number of hard links */ uid_t st_uid; /* [XSI] User ID of the file */ gid_t st_gid; /* [XSI] Group ID of the file */ dev_t st_rdev; /* [XSI] Device ID */ #if !defined(_POSIX_C_SOURCE) || defined(_DARWIN_C_SOURCE) struct timespec st_atimespec; /* time of last access */ struct timespec st_mtimespec; /* time of last data modification */ struct timespec st_ctimespec; /* time of last status change */ #else time_t st_atime; /* [XSI] Time of last access */ long st_atimensec; /* nsec of last access */ time_t st_mtime; /* [XSI] Last data modification time */ long st_mtimensec; /* last data modification nsec */ time_t st_ctime; /* [XSI] Time of last status change */ long st_ctimensec; /* nsec of last status change */ #endif off_t st_size; /* [XSI] file size, in bytes */ blkcnt_t st_blocks; /* [XSI] blocks allocated for file */ blksize_t st_blksize; /* [XSI] optimal blocksize for I/O */ __uint32_t st_flags; /* user defined flags for file */ __uint32_t st_gen; /* file generation number */ __int32_t st_lspare; /* RESERVED: DO NOT USE! */ __int64_t st_qspare[2]; /* RESERVED: DO NOT USE! */ };
stat函数
# 结构体 struct stat sbuf; # 将完整文件路径放入stat函数并将文件信息放到sbuf中 stat(filename, &sbuf); # 常用文件大小获取 sbuf.st_size
S_ISDIR判断是否为目录
# 通过存入stat结构体信息判断是否为目录 S_ISDIR(sbuf.st_mode)
S_ISREG判断是否为普通文件
# 通过存入stat结构体信息判断是否为普通文件 S_ISREG(sbuf.st_mode)