1.24 stat、lstat函数

 摘自:https://blog.csdn.net/m0_38062470/article/details/113574697

 

#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
 
int stat(const char *pathname, struct stat *buf);
作用:获取文件相关的信息
参数:
    -pathname:操作的文件的路径
    -buf:结构体变量,传出参数,用于保存获取到的文件的信息
返回值:
    成功:返回0
    失败:返回-1,设置errno
 
int lstat(const char *pathname, struct stat *buf);
参数:
    -pathname:操作的文件的路径
    -buf:结构体变量,传出参数,用于保存获取到的文件的信息
返回值:
    成功:返回0
    失败:返回-1,设置errno

 

 

//perror printf
#include <stdio.h>
//stat
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
 
int main()
{
    struct stat buf;
    int ret = stat("hello.txt",&buf);
    if(ret==-1)
    {
        perror("stat");
        return -1;
    }
    printf("size: %ld\n",buf.st_size);
    return 0;
}

 下面看lstat函数:

先给hello.txt创建一个软链接:

 

 通过stat命令查看hello.txt文件的信息:

 

 通过stat命令查看b.txt文件的信息:

 

 查看b.txt文件的内容:

 

 显示的实际上是hello.txt中的内容。

所以:

用stat函数获取软链接文件的信息,得到的实际是指向的文件的信息

用lstat函数获取软链接文件的信息,得到的是软链接文件本身的信息

posted @ 2024-02-05 10:23  LiuYanYGZ  阅读(2)  评论(0编辑  收藏  举报