Linux获取文件属性

以-rw-rw-r-- 1 ubuntu ubuntu 56 八月 1 19:37 1.txt 为例

一、stat函数

功能:获取文件的属性

函数原型:

cpp 复制代码
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>

int stat(const char *pathname, struct stat *statbuf);

参数:

char *pathname:指定要获取属性的文件路径以及名字

struct stat *statbuf:存储获取到的属性

返回值:

成功,返回0

失败,返回-1,更新errno

在Linux中封装的结构体:

cpp 复制代码
 struct stat {
               dev_t     st_dev;         /* ID of device containing file */
               ino_t     st_ino;         /* Inode number */             inode号
               mode_t    st_mode;        /* File type and mode */       文件类型以及权限
               nlink_t   st_nlink;       /* Number of hard links */     硬链接数
               uid_t     st_uid;         /* User ID of owner */         用户uid
               gid_t     st_gid;         /* Group ID of owner */        组用户gid
               dev_t     st_rdev;        /* Device ID (if special file) */
               off_t     st_size;        /* Total size, in bytes */     文件大小
               blksize_t st_blksize;     /* Block size for filesystem I/O */
               blkcnt_t  st_blocks;      /* Number of 512B blocks allocated */

               /* Since Linux 2.6, the kernel supports nanosecond
                  precision for the following timestamp fields.
                  For the details before Linux 2.6, see NOTES. */

               struct timespec st_atim;  /* Time of last access */     最后一次被访问的时间
               struct timespec st_mtim;  /* Time of last modification */     最后一次被修改的时间
               struct timespec st_ctim;  /* Time of last status change */     最后一次改变状态的时间

           #define st_atime st_atim.tv_sec      /* Backward compatibility */
           #define st_mtime st_mtim.tv_sec    
           #define st_ctime st_ctim.tv_sec
           };

打印文件属性:

cpp 复制代码
#include <stdio.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>

int main(int argc, const char *argv[])
{
	struct stat buf;
	if(stat("./1.txt",&buf) < 0)
	{
		perror("stat");
		return -1;
	}
	//获取文件类型和权限
	printf("0%o ",buf.st_mode);

	//获取文件的硬链接数
	printf("%ld ",buf.st_nlink);

	//获取文件所属用户
	printf("%d ",buf.st_uid);
	
	//获取文件所属组用户
	printf("%d ",buf.st_gid);

	//获取文件大小
	printf("%ld ",buf.st_size);

	//获取时间戳
	printf("%ld ",buf.st_ctime);
	return 0;
}

【输出样例】0100664 1 1000 1000 56 1690889850

使用stat函数输出的结果与Linux定义的文件属性输出样式有些不同,因此还需要进行一些处理

二、获取文件权限

cpp 复制代码
void get_filePermission(mode_t m)
{
	long x = 0400;
	char c[]="rwx";
	int count = 0; 
	while(x)
	{
		if((m & x) == 0)
			putchar('-');
		else
			printf("%c",c[count%3]);
		count++;
		x = x >> 1;
	}
	putchar(' ');
}

三、获取文件类型

cpp 复制代码
void get_fileType(mode_t m)
{
	if(S_ISREG(m))
		putchar('-');
	else if(S_ISDIR(m))
		putchar('d');
	else if(S_ISCHR(m))
		putchar('c');
	else if( S_ISBLK(m))
		putchar('b');
	else if( S_ISFIFO(m))
		putchar('p');
	else if( S_ISLNK(m))
		putchar('l');
	else if( S_ISSOCK(m))
		putchar('s');
}

四、获取文件所属用户名

getpwuid函数

功能:通过uid号获取用户的信息

函数原型:

cpp 复制代码
#include <sys/types.h>
#include <pwd.h>

struct passwd *getpwuid(uid_t uid);

参数:

uid_t uid:指定uid号

返回值:

成功,返回结构体指针

失败,返回NULL,更新errno

在Linux中封装的结构体:

cpp 复制代码
struct passwd {
    char   *pw_name;       /* username */
    char   *pw_passwd;     /* user password */
    uid_t   pw_uid;        /* user ID */
    gid_t   pw_gid;        /* group ID */
    char   *pw_gecos;      /* user information */
    char   *pw_dir;        /* home directory */
    char   *pw_shell;      /* shell program */
};

封装的函数:

cpp 复制代码
void get_fileUserName(uid_t uid)
{
    struct passwd *pwd = getpwuid(uid);
    if(NULL == pwd)
    {
        perror("getpwuid");
        return;
    }
    printf("%s\n",pwd->pw_name);
    return;
}

五、获取文件所属组用户名

getgrgid函数

功能:通过gid号获取组用户的信息

函数原型:

cpp 复制代码
#include <sys/types.h>
#include <grp.h>

struct group *getgrgid(gid_t gid);

参数:

gid_t gid:指定gid号

返回值:

成功,返回结构体指针

失败,返回NULL,更新errno

封装的函数:

cpp 复制代码
void get_fileGrpName(gid_t gid)
{
    struct group *grp = getgrgid(gid);
    if(NULL == grp)
    {
        perror("getgrgid");
        return;
    }
    printf("%s\n",grp->gr_name);
    return;
}

六、完整代码演示

cpp 复制代码
#include <stdio.h>
#include <string.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
#include <time.h>
#include <pwd.h>
#include <grp.h>
void get_fileType(mode_t m)
{
	if(S_ISREG(m))
		putchar('-');
	else if(S_ISDIR(m))
		putchar('d');
	else if(S_ISCHR(m))
		putchar('c');
	else if( S_ISBLK(m))
		putchar('b');
	else if( S_ISFIFO(m))
		putchar('p');
	else if( S_ISLNK(m))
		putchar('l');
	else if( S_ISSOCK(m))
		putchar('s');
}
void get_filePermission(mode_t m)
{
	long x = 0400;
	char c[]="rwx";
	int count = 0; 
	while(x)
	{
		if((m & x) == 0)
			putchar('-');
		else
			printf("%c",c[count%3]);
		count++;
		x = x >> 1;
	}
	putchar(' ');
}
int main(int argc, const char *argv[])
{
	struct stat buf;
	if(stat("./1.txt",&buf) < 0)
	{
		perror("stat");
		return -1;
	}
	//获取文件类型和权限
//	printf("0%o ",buf.st_mode);
	get_fileType(buf.st_mode);
	get_filePermission(buf.st_mode);

	//获取文件的硬链接数
	printf("%ld ",buf.st_nlink);

	//获取文件所属用户
//	printf("%d ",buf.st_uid);
	struct passwd *uid = getpwuid(buf.st_uid);
	printf("%s ",uid->pw_name);
	
	//获取文件所属组用户
//	printf("%d ",buf.st_gid);
	struct group *gid = getgrgid(buf.st_gid);
	printf("%s ",gid->gr_name);

	//获取文件大小
	printf("%ld ",buf.st_size);

	//获取时间戳
	struct tm *info=NULL;
	info = localtime(&buf.st_mtime);
//	printf("%ld ",buf.st_ctime);
	printf("%02d %02d %02d:%02d ",info->tm_mon+1,info->tm_mday,info->tm_hour,info->tm_min);
	printf("1.txt\n");
	return 0;
}
相关推荐
海鸥两三2 分钟前
基于 Vue 3 + 高德地图的网格规划系统实战(有源码)
前端·javascript·vue.js
Li-Yongjun3 分钟前
Linux 内核等待队列(Wait Queue)
linux·运维·windows
字节高级特工5 分钟前
【Linux】深入理解C语言命令行参数与环境变量
linux·c++·人工智能·后端
linux开发之路9 分钟前
C++项目推荐:eBPF+调度器性能分析框架
linux·c++·ebpf·火焰图·调度器
丷丩11 分钟前
MapLibre GL JS第11课:获取鼠标指针坐标
前端·javascript·gis·地图·mapbox·maplibre gl js
愿天垂怜15 分钟前
【C++脚手架】ffmpeg 库的介绍与使用
linux·服务器·开发语言·c++·ide·git·ffmpeg
代码AI弗森19 分钟前
前端周刊第 467 期[特殊字符] 本期精选目录
前端
jimy119 分钟前
Linux动态加载器,loader,dynamic linker
linux·运维·服务器
随便的名字20 分钟前
前端路由的底层逻辑:URL 中 # 和 ? 的区别与关系详解
前端
kongba00722 分钟前
ttyd Web终端安装指南(OpenCloudOS 9)
linux·前端