man 2 stat
STAT(2) Linux Programmer’s Manual STAT(2)
NAME
stat, fstat, lstat - get file status
SYNOPSIS
//头文件
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
int stat(const char *path, struct stat *buf);
int fstat(int filedes, struct stat *buf);
int lstat(const char *path, struct stat *buf);
参数path 文件路路径名称 buf 结构体的指针
DESCRIPTION
These functions return information about a file. No permissions are
required on the file itself, but — in the case of stat() and lstat() —
execute (search) permission is required on all of the directories in
path that lead to the file.
stat() stats the file pointed to by path and fills in buf.
lstat() is identical to stat(), except that if path is a symbolic link,
then the link itself is stat-ed, not the file that it refers to.
fstat() is identical to stat(), except that the file to be stat-ed is
specified by the file descriptor filedes.
All of these system calls return a stat structure, which contains the
following fields:
struct stat {
dev_t st_dev; /* ID of device containing file */
ino_t st_ino; /* inode number */
mode_t st_mode; /* protection */
nlink_t st_nlink; /* number of hard links */
uid_t st_uid; /* user ID of owner */
gid_t st_gid; /* group ID of owner */
dev_t st_rdev; /* device ID (if special file) */
off_t st_size; /* total size, in bytes */
blksize_t st_blksize; /* blocksize for filesystem I/O */
blkcnt_t st_blocks; /* number of blocks allocated */
time_t st_atime; /* time of last access */
time_t st_mtime; /* time of last modification */
time_t st_ctime; /* time of last status change */
};
返回值 3个函数的返回值:成功返回 0 失败返回 -1;
宏:
struct stat buf;
lstat("路径",&buf);
S_ISREG();普通文件
S_ISDIR();目录文件
S_ISCHR();字符设备
S_ISBLK();块设备
S_ISFIFO();管道
S_ISLNK();链接
S_ISSOCK()套接字
例子:
#include <stdlib.h>
#include <stdio.h>
int main(int argc,char *argv[])
{
int i;
struct stat buf;
char *ptr;
for(i=1;i<argc;i++)
{
printf("%s: ",argv[i]);
if(lstat(argv[i],&buf)<0)
{
perror("lstat");
continue;
}
if(S_ISREG(buf.st_mode))
ptr = "regular file";
else if(S_ISDIR(buf.st_mode))
ptr = "directory file";
else if(S_ISCHR(buf.st_mode))
ptr = "character special file";
else if(S_ISBLK(buf.st_mode))
ptr = "block special file";
else if(S_ISFIFO(buf.st_mode))
ptr = "FIFO file";
else if(S_ISLNK(buf.st_mode))
ptr = "link file";
else if(S_ISSOCK(buf.st_mode))
ptr = "socket file";
printf("%s\n",ptr);
}
return 0;