编程实现“ls -l 文件名”功能
getpwuid
getgrgid
localtime或ctime
ctime函数在C库中,头文件为<time.h>
函数原型:
char *ctime (const time_t *__timer)
作用:返回一个表示当地时间的字符串,当地时间是基于参数 timer
文章中的有些参数,需要自己用man函数自己查阅才能明白,比如switch函数
["code:c"]
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
#include <stdio.h>
#include <pwd.h>
#include <grp.h>
#include <time.h>
int main(int argc, char const *argv[])
{
struct stat st;
if (stat(argv[1], &st) < 0)
{
perror("stat err");
return -1;
}
printf("st_mode: %#o\n", st.st_mode);
//判断文件类型
switch (st.st_mode & S_IFMT)
{
case S_IFREG:
printf("-");
break;
case S_IFDIR:
printf("d");
break;
case S_IFCHR:
printf("c");
break;
case S_IFIFO:
printf("f");
break;
case S_IFLNK:
printf("l");
break;
case S_IFBLK:
printf("b");
break;
case S_IFSOCK:
printf("s");
break;
default:
printf("mode err\n");
break;
}
//判断文件权限
//个人权限
if (st.st_mode & S_IRUSR)
printf("r");
else
printf("-");
if (st.st_mode & S_IWUSR)
printf("w");
else
printf("-");
if ((st.st_mode & S_IXUSR))
printf("x");
else
printf("-");
//小组权限
if (st.st_mode & S_IRGRP)
printf("r");
else
printf("-");
if (st.st_mode & S_IWGRP)
printf("w");
else
printf("-");
if ((st.st_mode & S_IXGRP))
printf("x");
else
printf("-");
//其他人权限
if (st.st_mode & S_IROTH)
printf("r");
else
printf("-");
if (st.st_mode & S_IWOTH)
printf("w");
else
printf("-");
if ((st.st_mode & S_IXOTH))
printf("x");
else
printf("-");
//硬链接
printf(" %d", st.st_nlink);
//用户名 getpwuid()
printf(" %s", getpwuid(st.st_uid)->pw_name);
//组名 getgrgid()
printf(" %s", getgrgid(st.st_gid)->gr_name);
//文件大小
printf(" %ld", st.st_size);
//最后修改的时间 ctime()
printf(" %.12s", ctime(&st.st_mtime) + 4);//+4:偏移4地址跳过前4位,.12:只打印12个字符
//名字:
printf(" %s\n", argv[1]);
return 0;
}