函数声明如下
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
int stat(const char *path, struct stat *buf);
int fstat(int fd, struct stat *buf);
int lstat(const char *path, struct stat *buf);
三个函数的返回值:若成功则返回0,若出错则返回-1
stat函数根据pathname路径返回与此命名文件有关的信息结构
fstat根据文件描述符获取有关信息结构
lstat类似于stat,但是当命名文件是一个符号链接时,lstat返回该符号链接的有关信息,而不是由该符号链接引用的文件信息
该结构体的基本形式
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 file system I/O */
blkcnt_t st_blocks; /* number of 512B 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 */
};
文件类型信息包含在stat结构的st_mode成员中。可用宏确定文件类型。这些宏的参数都是stat结构中的st_mode成员
S_ISREG(m) 普通文件
S_ISDIR(m) 目录
S_ISCHR(m) 字符特殊文件
S_ISBLK(m) 块特殊文件
S_ISFIFO(m) 管道或FIFO文件
S_ISLNK(m) 符号链接
S_ISSOCK(m) 套接子
#include <sys/stat.h>
#include <stdio.h>
#include <stdlib.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) {
printf("lstat error\n");
continue;
}
if (S_ISREG(buf.st_mode))
ptr = "普通文件";
else if (S_ISCHR(buf.st_mode))
ptr = "目录文件";
else if (S_ISCHR(buf.st_mode))
ptr = "字符特殊文件";
else if (S_ISBLK(buf.st_mode))
ptr = "块特殊文件";
else if (S_ISFIFO(buf.st_mode))
ptr = "管道或FIFO文件";
else if (S_ISLNK(buf.st_mode))
ptr = "符号链接";
else if (S_ISSOCK(buf.st_mode))
ptr = "socket文件";
else
ptr = "未知类型";
printf("%s\n", ptr);
}
return 0;
}
在终端中输入命令行参数
./a.out /etc/passwd /dev/log \
> /dev/cdrom
运行结果:
/etc/passwd: 普通文件
/dev/log: socket文件
/dev/cdrom: 符号链接