栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 系统运维 > 运维 > Linux

linux下的stat/lstat函数

Linux 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

linux下的stat/lstat函数

Linux 下可以使用 stat 命令查看文件的属性,其实这个命令内部就是通过调用 stat() 函数来获取文件属性的,stat 函数是 Linux 中的系统调用,用于获取文件相关的信息,函数原型如下所示(可通过 "man 2 stat"命令查看):
#include 
#include 
#include 
int stat/lstat(const char *pathname, struct stat *buf);
pathname : 用于指定一个需要查看属性的文件路径。 buf : struct stat 类型指针,用于指向一个 struct stat 结构体变量。调用 stat 函数的时候需要传入一个 struct stat 变量的指针,获取到的文件属性信息就记录在 struct stat 结构体中。 成返回 0 ;失败返回 -1 设置 errno 为恰当值。 struct stat 结构体
struct stat
{
 dev_t st_dev; 
 ino_t st_ino; 
 mode_t st_mode; 
 nlink_t st_nlink; 
 uid_t st_uid; 
 gid_t st_gid; 
 dev_t st_rdev; 
 off_t st_size; 
 blksize_t st_blksize; 
 blkcnt_t st_blocks; 
 struct timespec st_atim; 
 struct timespec st_mtim; 
 struct timespec st_ctim; 
};

获取文件大小: buf.st_size
#include 
#include 
#include 
#include 
int main(void)
{	
	struct stat sbuf;
	int ret = stat("test", &sbuf);
	if(ret == -1)
	{
		perror("stat error");
		exit(1);
	}
	printf("file size %ldn",sbuf.st_size);
	return 0;
}

获取文件类型: buf.st_mode

文件类型判断方法: st_mode 取高 4 位。 但应使用宏函数: S_ISREG(m)              is it a regular file? S_ISDIR(m)                directory? S_ISCHR(m)              character device? S_ISBLK(m)               block device? S_ISFIFO(m)              FIFO (named pipe)? S_ISLNK(m)               symbolic link? (Not in POSIX.1-1996.) S_ISSOCK(m)            socket? (Not in POSIX.1-1996.)
#include 
#include 
#include 
#include 
int main(int argc, char *argv[])
{
	struct stat sbuf;
	int ret = stat/lstat(argv[1], &sbuf);
	if(ret == -1)
	{
		perror("stat error");
		exit(1);
	}
	if(S_ISREG(sbuf.st_mode)) {
		printf("it is a regularn");	
	} else if(S_ISDIR(sbuf.st_mode)) {
		printf("it is a directoryn"); 
	} else if(S_ISFIFO(sbuf.st_mode)) {
		printf("it is a pipen");
	} else if(S_ISLNK(sbuf.st_mode)) {
		printf("it is a sym linkn");
	}
	return 0;
}
穿透符号链接: stat :会; lstat :不会 lstat() 与 sta t 的区别在于,对于符号链接文件, stat   查阅的是符号链接文件所指向的文件对应的文件属性信息,而 lstat 查阅的是符号链接文件本身的属性信息。(其实像cat vim 命令都是穿透的,而ls -l 不是穿透的,所以命令都是用系统调用实现的)
转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/334949.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号