Linux
下可以使用
stat
命令查看文件的属性,其实这个命令内部就是通过调用
stat()
函数来获取文件属性的,stat
函数是
Linux
中的系统调用,用于获取文件相关的信息,函数原型如下所示(可通过
"man 2 stat"命令查看):
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
int stat/lstat(const char *pathname, struct stat *buf);
pathname
:
用于指定一个需要查看属性的文件路径。
buf
:
struct stat
类型指针,用于指向一个
struct stat
结构体变量。调用
stat
函数的时候需要传入一个
struct stat 变量的指针,获取到的文件属性信息就记录在
struct stat
结构体中。
成返回
0
;失败返回
-1
设置
errno
为恰当值。
struct stat
结构体
struct stat
{
dev_t st_dev; /* 文件所在设备的 ID */
ino_t st_ino; /* 文件对应 inode 节点编号 */
mode_t st_mode; /* 文件对应的模式 */
nlink_t st_nlink; /* 文件的链接数 */
uid_t st_uid; /* 文件所有者的用户 ID */
gid_t st_gid; /* 文件所有者的组 ID */
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 <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/stat.h>
int main(void)
{
struct stat sbuf;
int ret = stat("test", &sbuf);
if(ret == -1)
{
perror("stat error");
exit(1);
}
printf("file size %ld\n",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 <stdio.h>
#include <sys/stat.h>
#include <stdlib.h>
#include <unistd.h>
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 regular\n");
} else if(S_ISDIR(sbuf.st_mode)) {
printf("it is a directory\n");
} else if(S_ISFIFO(sbuf.st_mode)) {
printf("it is a pipe\n");
} else if(S_ISLNK(sbuf.st_mode)) {
printf("it is a sym link\n");
}
return 0;
}
穿透符号链接:
stat
:会;
lstat
:不会
lstat()
与
sta
t
的区别在于,对于符号链接文件,
stat
查阅的是符号链接文件所指向的文件对应的文件属性信息,而 lstat
查阅的是符号链接文件本身的属性信息。(其实像cat vim 命令都是穿透的,而ls -l 不是穿透的,所以命令都是用系统调用实现的)