stat ()、fstat()、fstat()函数及其使用方式

1. stat ()

函数原型如下所示:
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>


int stat(const char *pathname, struct stat *buf);

函数参数及返回值含义如下:
pathname:用于指定一个需要查看属性的文件路径。
buf:struct stat 类型指针,用于指向一个 struct stat 结构体变量。调用 stat 函数的时候需要传入一个 struct。


stat 变量的指针,获取到的文件属性信息就记录在 struct stat 结构体中。
返回值:成功返回 0;失败返回-1,并设置 error。

        stat ()函数是一个用于获取文件属性的系统调用,它返回一个包含文件元数据的结构体。在C语言中,可以使用`stat`函数来获取文件的信息,如文件大小、权限、创建时间等。stat() 函数的使用方式如下:


#include <sys/stat.h>
#include <stdio.h>

int main() {
    struct stat fileStat;
    if (stat("file.txt", &fileStat) == 0) {
        printf("File Size: %ld bytes\n", fileStat.st_size);
        printf("File Permissions: %o\n", fileStat.st_mode);
        // 其他属性
    } else {
        perror("Error in stat");
    }
    return 0;
}

2. fstat()

fstat 函数原型如下:

#include <sys/types.h>

#include <sys/stat.h>

#include <unistd.h>

int fstat(int fd, struct stat *buf);

        fstat() 函数与 stat() 函数类似,不同之处在于它接受一个文件描述符作为参数,而不是文件名。使用方式如下:


#include <sys/stat.h>
#include <fcntl.h>
#include <stdio.h>

int main() {
    int fd = open("file.txt", O_RDONLY);
    if (fd != -1) {
        struct stat fileStat;
        if (fstat(fd, &fileStat) == 0) {
            printf("File Size: %ld bytes\n", fileStat.st_size);
            printf("File Permissions: %o\n", fileStat.st_mode);
            // 其他属性
        } else {
            perror("Error in fstat");
        }
        close(fd);
    } else {
        perror("Error opening file");
    }
    return 0;
}

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

函数参数列表、返回值与 stat 函数一样,使用方法也一样。

  • 20
    点赞
  • 12
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值