#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);
stat的定义:
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 */
};
文件类型
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.)
函数说明 fstat()用来将参数fildes所指的文件状态,复制到参数buf所指的
结构中(struct stat)。fstat()与stat()作用完全相同,不同处在
于传入的参数为已打开的文件描述词。详细内容请参考stat()。
返回值 执行成功则返回0,失败返回-1,错误代码存于errno。
设备号是16位的二进制,高八位主设备号(int)((unsigned short )a>>8),第八位次设备号(int)((unsigned short )a&0xFF)
主设备号决定是用什么驱动程序访问设备,次设备号区分某一设备的各个类别如:
/dev/sda1
/dev/sda2
df命令访问某文件分区
例:获取某文件的文件状态
int main(int arg, char *args[])
{
if (arg < 2)
{
printf("open file error");
return -1;
}
int fd = open(args[1], O_RDONLY);
if (fd == -1)
{
printf("error occur %s\n", strerror(errno));
} else
{
printf("the fd = %d\n", fd);
struct stat tmp;
int i = stat(args[1],&tmp);
if(i==-1)
{
printf("error\n");
close(fd);
return -1;
}
else
{
if(S_ISREG(tmp.st_mode))
printf("S_ISREG\n");
printf("%d\n",S_ISDIR(tmp.st_mode));
printf("%d\n",tmp.st_uid);
}
close(fd);
}
return 0;
}