#includepathname : 用于指定一个需要查看属性的文件路径。 buf : struct stat 类型指针,用于指向一个 struct stat 结构体变量。调用 stat 函数的时候需要传入一个 struct stat 变量的指针,获取到的文件属性信息就记录在 struct stat 结构体中。 成返回 0 ;失败返回 -1 设置 errno 为恰当值。 struct stat 结构体#include #include int stat/lstat(const char *pathname, struct stat *buf);
struct stat
{
dev_t st_dev;
ino_t st_ino;
mode_t st_mode;
nlink_t st_nlink;
uid_t st_uid;
gid_t st_gid;
dev_t st_rdev;
off_t st_size;
blksize_t st_blksize;
blkcnt_t st_blocks;
struct timespec st_atim;
struct timespec st_mtim;
struct timespec st_ctim;
};
获取文件大小: buf.st_size
#include#include #include #include int main(void) { struct stat sbuf; int ret = stat("test", &sbuf); if(ret == -1) { perror("stat error"); exit(1); } printf("file size %ldn",sbuf.st_size); return 0; }
获取文件类型: buf.st_mode
文件类型判断方法: st_mode 取高 4 位。 但应使用宏函数: S_ISREG(m) is it a regular file? S_ISDIR(m) directory? S_ISCHR(m) character device? S_ISBLK(m) block device? S_ISFIFO(m) FIFO (named pipe)? S_ISLNK(m) symbolic link? (Not in POSIX.1-1996.) S_ISSOCK(m) socket? (Not in POSIX.1-1996.)#include穿透符号链接: stat :会; lstat :不会 lstat() 与 sta t 的区别在于,对于符号链接文件, stat 查阅的是符号链接文件所指向的文件对应的文件属性信息,而 lstat 查阅的是符号链接文件本身的属性信息。(其实像cat vim 命令都是穿透的,而ls -l 不是穿透的,所以命令都是用系统调用实现的)#include #include #include int main(int argc, char *argv[]) { struct stat sbuf; int ret = stat/lstat(argv[1], &sbuf); if(ret == -1) { perror("stat error"); exit(1); } if(S_ISREG(sbuf.st_mode)) { printf("it is a regularn"); } else if(S_ISDIR(sbuf.st_mode)) { printf("it is a directoryn"); } else if(S_ISFIFO(sbuf.st_mode)) { printf("it is a pipen"); } else if(S_ISLNK(sbuf.st_mode)) { printf("it is a sym linkn"); } return 0; }



