stat、fstat和lstat函数
来源:互联网 发布:2017网络新技术 编辑:程序博客网 时间:2024/05/22 00:47
函数声明如下
#include <sys/types.h>#include <sys/stat.h>#include <unistd.h>int stat(const char *path, struct stat *buf);int fstat(int fd, struct stat *buf);int lstat(const char *path, struct stat *buf);
三个函数的返回值:若成功则返回0,若出错则返回-1
stat函数根据pathname路径返回与此命名文件有关的信息结构
fstat根据文件描述符获取有关信息结构
lstat类似于stat,但是当命名文件是一个符号链接时,lstat返回该符号链接的有关信息,而不是由该符号链接引用的文件信息
该结构体的基本形式
struct stat { dev_t st_dev; /* ID of device containing file */ ino_t st_ino; /* inode number */ mode_t st_mode; /* protection */ nlink_t st_nlink; /* number of hard links */ uid_t st_uid; /* user ID of owner */ gid_t st_gid; /* group ID of owner */ dev_t st_rdev; /* device ID (if special file) */ off_t st_size; /* total size, in bytes */ blksize_t st_blksize; /* blocksize for file system I/O */ blkcnt_t st_blocks; /* number of 512B blocks allocated */ time_t st_atime; /* time of last access */ time_t st_mtime; /* time of last modification */ time_t st_ctime; /* time of last status change */};
文件类型信息包含在stat结构的st_mode成员中。可用宏确定文件类型。这些宏的参数都是stat结构中的st_mode成员
S_ISREG(m) 普通文件
S_ISDIR(m) 目录
S_ISCHR(m) 字符特殊文件
S_ISBLK(m) 块特殊文件
S_ISFIFO(m) 管道或FIFO文件
S_ISLNK(m) 符号链接
S_ISSOCK(m) 套接子
#include <sys/stat.h>#include <stdio.h>#include <stdlib.h>int main(int argc, char *argv[]){int i;struct stat buf;char *ptr;for (i=1; i<argc; i++) {printf("%s: ", argv[i]);if (lstat(argv[i], &buf) < 0) {printf("lstat error\n");continue;}if (S_ISREG(buf.st_mode))ptr = "普通文件";else if (S_ISCHR(buf.st_mode))ptr = "目录文件";else if (S_ISCHR(buf.st_mode))ptr = "字符特殊文件";else if (S_ISBLK(buf.st_mode))ptr = "块特殊文件";else if (S_ISFIFO(buf.st_mode))ptr = "管道或FIFO文件";else if (S_ISLNK(buf.st_mode))ptr = "符号链接";else if (S_ISSOCK(buf.st_mode))ptr = "socket文件";else ptr = "未知类型";printf("%s\n", ptr);}return 0;}
在终端中输入命令行参数
./a.out /etc/passwd /dev/log \
> /dev/cdrom
运行结果:
/etc/passwd: 普通文件
/dev/log: socket文件
/dev/cdrom: 符号链接
0 0
- stat、fstat和lstat函数
- stat、fstat和lstat函数
- stat/fstat/lstat函数
- stat, fstat, lstat 函数
- stat、fstat、lstat函数
- stat/fstat/lstat函数
- stat函数(fstat和lstat函数)
- C语言:stat,fstat和lstat函数
- C语言:stat,fstat和lstat函数
- UNIX--stat、fstat和lstat函数
- stat,fstat和lstat函数使用
- stat、fstat和lstat函数详解
- Linux stat、fstat和lstat函数
- 函数stat,fstat,fstatat和lstat
- stat,fstat以及lstat函数
- stat,fstat以及lstat函数
- 文件属性函数stat/fstat/lstat
- stat,fstat以及lstat函数
- 高斯消元法模板
- 唯一索引引发的行锁
- 布隆过滤器在网咯爬虫中的应用
- 死锁
- 一个简单通用的应用程序makefile
- stat、fstat和lstat函数
- LeetCode OJ --问题与解答 Reverse Words in a String
- lucene创建索引
- javascript实现限制上传文件的大小
- Linux 线程学习
- 连载了解SIP协议翻译文章[IOKE作品]
- DevSuite助力北京拓敏,管理产品研发全过程
- 结构化程序设计----分支结构
- Mac OSX系统 RODBC连接Mysql数据库乱码的解决方法