stat、lstat、fstat的区别
函数原型:
int stat(const char *path, struct stat *buf);
int lstat(const char *path, struct stat *buf);
int fstat(int fd, struct stat *buf);
lstat函数和stat函数作用是类似的,只不过当要读取的文件是符号链接文件时,lstat函数获取的是符号链接文件的属性,而stat函数获取的是符号链接文件指向的实际文件的属性。
#include<stdlib.h>
#include<stdio.h>
#include<sys/types.h>
#include<sys/stat.h>
#include<unistd.h>
int main(int argc,char*argv[])
{
if(argc<2)
{
printf("need filename");
exit(1);
}
struct stat st;
int ret = stat(argv[1],&st);//(1)
int ret = lstat(argv[1],&st);//(2)
int size = (int)st.st_size;//使用(1)(2)的区别是,当要读取的文件是链接文件时,那么(1)会读取源文件的大小,(2)会读取链接文件的大小。
printf("file size = %d \n",size);
return 0;
}
fstat与stat都是取文件的信息,只是函数原型不同。stat的参数可以直接写文件名。而fstat需要先打开文件,然后用文件描述符fd做参数。