#include <stdio.h>
#include <unistd.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <stdlib.h>
#include <pwd.h>
#include <grp.h>
#include <time.h>
#include <string.h>
//模拟实现ls -l
//-rw-rw-r-- 1 nowcoder nowcoder 12 12月 3 12:48 a.txt
int main(int argc, char *argv[])
{
if(argc < 2)
{
printf("%s filename\n", argv[0]);
return -1;
}
// 使用stat接受文件的信息
struct stat st;
int ret = stat(argv[1], &st);
if(ret < 0)
{
perror("stat");
return -1;
}
char buf[11] = {0};
switch(st.st_mode&S_IFMT)
{
case S_IFSOCK:
buf[0] = 's';
break;
case S_IFDIR:
buf[0] = 'd';
break;
case S_IFCHR:
buf[0] = 'c';
break;
case S_IFLNK:
buf[0] = 'l';
break;
case S_IFIFO:
buf[0] = 'p'; //注意管道文件显示p
break;
case S_IFMT:
buf[0] = 'm';
break;
case S_IFREG:
buf[0] = '-';
break;
case S_IFBLK:
buf[0] = 'b';
break;
default:
buf[0] = '?';
break;
}
// 判断文件的访问权限
//判断文件的所有者
buf[1] = (st.st_mode & S_IRUSR) ? 'r': '-';
buf[2] = (st.st_mode & S_IWUSR) ? 'w': '-';
buf[3] = (st.st_mode & S_IXUSR) ? 'x': '-';
//判断文件的组
buf[4] = (st.st_mode & S_IRGRP) ? 'r': '-';
buf[5] = (st.st_mode & S_IWGRP) ? 'w': '-';
buf[6] = (st.st_mode & S_IXGRP) ? 'x': '-';
//判断文件的其他
buf[7] = (st.st_mode & S_IROTH) ? 'r': '-';
buf[8] = (st.st_mode & S_IWOTH) ? 'w': '-';
buf[9] = (st.st_mode & S_IXOTH) ? 'x': '-';
//硬连接数
int linknum = st.st_nlink;
//文件的所有者
//st结构体里面只有文件的所有者的id
char *fileuser = getpwuid(st.st_uid)->pw_name;
//文件所在的组
char *fliegroup = getgrgid(st.st_gid)->gr_name;
//文件的大小
long int filesize = st.st_size;
//获取修改时间,获取的时间实际上是秒数,从1980年开始
char *time = ctime(&st.st_mtime);
char temp[50] ={0};
strncpy(temp, time, strlen(time)-1);
char buflong[1024];
sprintf(buflong, "%s %d %s %s %ld %s %s", buf, linknum, fileuser, fliegroup, filesize, temp, argv[1]);
printf("%s\n", buflong);
return 0;
}
ls-l的实现
于 2022-01-11 21:58:54 首次发布