栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 系统运维 > 运维 > Linux

32.Linux stat函数

Linux 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

32.Linux stat函数

获取文件属性,(从inode结构体中获取)

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

返回值:

成功返回0;

失败返回-1;

设置errno为恰当值

参数1:文件路径

参数2:inode结构体指针(传出参数)

 文件属性将通过传出参数返回给调用者

练习:使用stat函数查看文件属性

stat.c(查看st_size)(获取文件大小:buf.st_size)

#include 
#include 
#include 
#include 
#include 
#include 
int main(int argc,char *argv[])
{
        struct stat sbuf;

        int ret = stat(argv[1],&sbuf); 
        if(ret == -1)
        {
                perror("stat error");
                exit(1);
        }

        printf("file size:%ldn",sbuf.st_size);

        return 0;
}

执行结果如下:

 只要是inode结构体里面有的东西都可以

如果查看文件类型:

在st_mode里面可以这样玩:(获取文件类型)

#include 
#include 
#include 
#include 
#include 
#include 
int main(int argc,char *argv[])
{
        struct stat sbuf;

        int ret = stat(argv[1],&sbuf);
        if(ret == -1)
        {
                perror("stat error");
                exit(1);
        }

        if(S_ISREG(sbuf.st_mode))        //判断文件是否为普通文件
        {
                printf("It's a regularn");
        } 
        else if(S_ISDIR(sbuf.st_mode))   //判断文件是否为目录,下面都一样
        {
                printf("It's a dirn");
        }
        else if(S_ISFIFO(sbuf.st_mode))
        {
                printf("It's a pipe");
        }
        else if(S_ISLNK(sbuf.st_mode))
        {
                printf("It's a sym linkn");
        }

        return 0;
}

执行结果如下:

 创建管道文件:mkfifo f2

 创建符号链接:

sudo ln -s f f1.soft

给目录创建符号链接:

ln -s mydir dir.s

 ls -ld dir.s/

查看目录文件

 

默认stat函数穿透符号链接

而lstat函数不会穿透符号链接 

#include 
#include 
#include 
#include 
#include 
#include 
int main(int argc,char *argv[])
{
        struct stat sbuf;

        int ret = lstat(argv[1],&sbuf);  //只需要修改为lstat就不会穿透符号链接
        if(ret == -1)
        {
                perror("stat error");
                exit(1);
        }

        if(S_ISREG(sbuf.st_mode))
        {
                printf("It's a regularn");
        }
        else if(S_ISDIR(sbuf.st_mode))
        {
                printf("It's a dirn");
        }
        else if(S_ISFIFO(sbuf.st_mode))
        {
                printf("It's a pipen");
        }
        else if(S_ISLNK(sbuf.st_mode))
        {
                printf("It's a sym linkn");
        }

        return 0;
}

执行结果如下:

 

 

符号穿透:stat会    lstat不会

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/334831.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号