Linux获取文件属性
以-rw-rw-r-- 1 ubuntu ubuntu 56 八月 1 19:37 1.txt 为例
一、stat函数
功能:获取文件的属性
函数原型:
#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中封装的结构体:
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 */ 用户uidgid_t st_gid; /* Group ID of owner */ 组用户giddev_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 nanosecondprecision 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};
打印文件属性:
#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定义的文件属性输出样式有些不同,因此还需要进行一些处理
二、获取文件权限
void get_filePermission(mode_t m)
{long x = 0400;char c[]="rwx";int count = 0; while(x){if((m & x) == 0)putchar('-');elseprintf("%c",c[count%3]);count++;x = x >> 1;}putchar(' ');
}
三、获取文件类型
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号获取用户的信息
函数原型:
#include <sys/types.h>
#include <pwd.h>struct passwd *getpwuid(uid_t uid);
参数:
uid_t uid:指定uid号
返回值:
成功,返回结构体指针
失败,返回NULL,更新errno
在Linux中封装的结构体:
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 */
};
封装的函数:
void get_fileUserName(uid_t uid)
{struct passwd *pwd = getwuid(uid);if(NULL == pwd){perror("getpwuid");return;}printf("%s\n",pwd->pw_name);return;
}