Linux 下可以使用 stat 命令查看文件的属性,其实这个命令内部就是通过调用 stat()函数来获取文件属性的,stat 函数是 Linux 中的系统调用,用于获取文件相关的信息,函数原型如下所示(可通过"man 2 stat" 命令查看):
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
int stat(const char *pathname, struct stat *buf);
除了 stat 函数之外,还可以使用 fstat 和 lstat 两个系统调用来获 取文件属性信息。fstat、lstat 与 stat 的作用一样,但是参数、细节方面有些许不同。
fstat函数
fstat 与 stat 区别在于,stat 是从文件名出发得到文件属性信息,不需要先打开文件;而 fstat 函数则是从 文件描述符出发得到文件属性信息,所以使用 fstat 函数之前需要先打开文件得到文件描述符。具体该用 stat 还是 fstat,看具体的情况;譬如,并不想通过打开文件来得到文件属性信息,那么就使用 stat,如果文件已 经打开了,那么就使用 fstat。
fstat 函数原型如下(可通过"man 2 fstat"命令查看):
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
int fstat(int fd, struct stat *buf);
第一个参数 fd 表示文件描述符,第二个参数以及返回值与 stat 一样。fstat 函数示例如下:
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
#include <stdio.h>
#include <stdlib.h>
int main(void)
{
struct stat file_stat;
int fd;
int ret;
/* 打开文件 */
fd = open("./test_file", O_RDONLY);
if (-1 == fd) {
perror("open error");
exit(-1);
}
/* 获取文件属性 */
ret = fstat(fd, &file_stat);
if (-1 == ret)
perror("fstat error");
close(fd);
exit(ret);
}
lstat函数
lstat()与 stat、fstat 的区别在于,对于符号链接文件,stat、fstat 查阅的是符号链接文件所指向的文件对 应的文件属性信息,而 lstat 查阅的是符号链接文件本身的属性信息。
lstat 函数原型如下所示:
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
int lstat(const char *pathname, struct stat *buf);