使用函数实现Linux ls -li 功能
#include <stdio.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
#include <time.h>
#include <sys/types.h>
#include <grp.h>
#include <pwd.h>
int main(int argc, char const *argv[])
{
if (argc != 2)
{
printf("使用格式:%s <file>\n", argv[0]);
return -1;
}
struct stat s;
if (stat(argv[1], &s) > 0)
{
perror("stat err");
return -1;
}
//ino
printf("%lu ", s.st_ino);
//文件类型与权限
//文件类型
switch (s.st_mode & S_IFMT)
{
case S_IFSOCK:
printf("s");
break;
case S_IFLNK:
printf("l");
break;
case S_IFREG:
printf("-");
break;
case S_IFBLK:
printf("b");
break;
case S_IFDIR:
printf("d");
break;
case S_IFCHR:
printf("c");
break;
case S_IFIFO:
printf("p");
break;
}
//个人权限
if (s.st_mode & S_IRUSR)
putchar('r');
else
putchar('-');
if (s.st_mode & S_IWUSR)
putchar('w');
else
putchar('-');
if (s.st_mode & S_IXUSR)
putchar('x');
else
putchar('-');
//组权限
if (s.st_mode & S_IRGRP)
putchar('r');
else
putchar('-');
if (s.st_mode & S_IWGRP)
putchar('w');
else
putchar('-');
if (s.st_mode & S_IXGRP)
putchar('x');
else
putchar('-');
//其他用户权限
if (s.st_mode & S_IROTH)
putchar('r');
else
putchar('-');
if (s.st_mode & S_IWOTH)
putchar('w');
else
putchar('-');
if (s.st_mode & S_IXOTH)
printf("x ");
else
printf("- ");
//硬链接数
printf("%u ", s.st_nlink);
//用户名
struct passwd *pr = getpwuid(s.st_uid);
printf("%s ", pr->pw_name);
//组名
struct group *gr = getgrgid(s.st_gid);
printf("%s ", gr->gr_name);
//文件大小(总字节数)
printf("%lu ", s.st_size);
//时间
time_t t = s.st_mtime;
struct tm *time=localtime(&t);
printf("%d月 %d %d:%d ", time->tm_mon + 1, time->tm_mday, time->tm_hour, time->tm_min);
printf("%s\n",argv[1]);
return 0;
}
权限处可进行优化,代码如下:
//权限
char mod[4]="rwx-";
for(int i=0;i<9;i++)
{
printf("%c",(s.st_mode & (0400 >> i))?mod[i%3]:mod[3]);
}
putchar(32);