#include <stdio.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <string.h>
#include <time.h>
#include <pwd.h>
#include <grp.h>
int main(int argc,char *argv[])
{
if(argc != 2)
{
printf("./a.out filename\n");
return -1;
}
//调用stat 得到文件的属性信息
struct stat sb;
// stat(argv[1],&sb);
/*
*stat 碰到链接文件,会追溯到源文件,穿透!! lstat并不会
* */
lstat(argv[1],&sb);
//解析属性信息 st_mode uid gid time
//st_mode
char stmode[11] = {0};
memset(stmode,‘-‘,sizeof(stmode)-1);
stmode[0] = S_ISREG(sb.st_mode)?‘-‘:‘-‘;
stmode[0] = S_ISDIR(sb.st_mode)?‘d‘:stmode[0];
stmode[0] = S_ISCHR(sb.st_mode)?‘c‘:stmode[0];
stmode[0] = S_ISBLK(sb.st_mode)?‘b‘:stmode[0];
stmode[0] = S_ISFIFO(sb.st_mode)?‘p‘:stmode[0];
stmode[0] = S_ISLNK(sb.st_mode)?‘l‘:stmode[0];
stmode[0] = S_ISSOCK(sb.st_mode)?‘s‘:stmode[0];
//解析权限
stmode[1] = sb.st_mode & S_IRUSR?‘r‘:‘-‘;
stmode[2] = sb.st_mode & S_IWUSR?‘w‘:‘-‘;
stmode[3] = sb.st_mode & S_IXUSR?‘x‘:‘-‘;
stmode[4] = sb.st_mode & S_IRGRP?‘r‘:‘-‘;
stmode[5] = sb.st_mode & S_IWGRP?‘w‘:‘-‘;
stmode[6] = sb.st_mode & S_IXGRP?‘x‘:‘-‘;
stmode[7] = sb.st_mode & S_IROTH?‘r‘:‘-‘;
stmode[8] = sb.st_mode & S_IWOTH?‘w‘:‘-‘;
stmode[9] = sb.st_mode & S_IXOTH?‘x‘:‘-‘;
//分析用户名和组名通过函数获得 getpwuid getgrgid
//时间获取
struct tm *filetm = localtime(&sb.st_atim.tv_sec);
char timebuf[20]={0};
sprintf(timebuf,"%d月 %d %02d:%02d",filetm->tm_mon+1,filetm->tm_mday,filetm->tm_hour,filetm->tm_m
// sprintf("-rw-rw-r-- 1 xiaozhao xiaozhao 0 Feb 24 22:15 hello\n");
printf("%s %d %s %s %d %s %s\n",stmode,sb.st_nlink,getpwuid(sb.st_uid)->pw_name,
getgrgid(sb.st_gid)->gr_name,sb.st_size,timebuf,argv[1]);
return 0;
}
原文:https://www.cnblogs.com/lodger47/p/14727622.html