fstat 和 lstat 函数

        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);

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值