#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函数获取软链接文件的信息,得到的是软链接文件本身的信息。
参考:牛客网 C++高薪求职项目《Linux高并发服务器开发》1.23 lseek函数
专属优惠链接:
https://www.nowcoder.com/courses/cover/live/504?coupon=AvTPnSG