获取文件属性,(从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不会



