zl程序教程

您现在的位置是:首页 >  系统

当前栏目

linux的stat命令_fstat函数

Linux命令 函数 stat fstat
2023-06-13 09:11:03 时间

大家好,又见面了,我是你们的朋友全栈君。

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

pathname 用于指定一个需要查看属性的文件路径。

buf struct stat 类型指针,用于指向一个 struct stat 结构体变量。调用 stat 函数的时候需要传入一个 struct stat

变量的指针,获取到的文件属性信息就记录在 struct stat 结构体中 。

返回值: 成功返回 0 ;失败返回 -1 ,并设置 error 。

示例代码: 获取文件的 inode 节点编号以及文件大小,并将它们打印出来。

#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
#include <stdio.h>
#include <stdlib.h>

int main(void)
{
    struct stat file_stat;
    int ret;
    /* 获取文件属性 */
    ret = stat("./test_file", &file_stat);
    if (-1 == ret)
    {
        perror("stat error");
        exit(-1);
    }
    /* 打印文件大小和 inode 编号 */
    printf("file size: %ld bytes\n"
           "inode number: %ld\n",
           file_stat.st_size,
           file_stat.st_ino);
    exit(0);
}

测试验证:

从图中可以得知,此文件的大小为 4060 个字节,inode 编号为 656929

接下来编译测试程序,并运行

发布者:全栈程序员栈长,转载请注明出处:https://javaforall.cn/171780.html原文链接:https://javaforall.cn