您的位置:首页 > 运维架构 > Linux

Linux基础:模拟ls -l命令的实现(环境ubutun)

2020-08-25 20:21 381 查看
#include <stdio.h>
#include <string.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <time.h>
#include <pwd.h>
#include <grp.h>

void file_type(mode_t mode)
{
switch(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;
}
}

void file_mode(mode_t mode)
{
printf("%c",mode & S_IRUSR?'r':'-');
printf("%c",mode & S_IWUSR?'w':'-');
printf("%c",mode & S_IXUSR?'x':'-');
printf("%c",mode & S_IRGRP?'r':'-');
printf("%c",mode & S_IWGRP?'w':'-');
printf("%c",mode & S_IXGRP?'x':'-');
printf("%c",mode & S_IROTH?'r':'-');
printf("%c",mode & S_IWOTH?'w':'-');
printf("%c",mode & S_IXOTH?'x':'-');
}

void user_name(uid_t uid)
{
struct passwd* pd =  getpwuid(uid);
printf("  %s",pd->pw_name);
}

void group_name(gid_t gid)
{
struct group * gp = getgrgid(gid);
printf(" %s",gp->gr_name);
}

void show_time(time_t mtime)
{
struct tm * t = localtime(&mtime);
printf("  %d月 %d %d:%d",t->tm_mon+1,t->tm_mday,t->tm_hour,t->tm_min);

}

void list_file_stat(const char* path)
{
// 获取文件属性
struct stat buf;
if(stat(path,&buf))
{
perror("stat");
return;
}

// 显示文件类型
file_type(buf.st_mode);
// 显示文件权限
file_mode(buf.st_mode);
// 显示目录层数
printf("  %c",S_ISDIR(buf.st_mode)?'2':'1');
// 显示用户名
user_name(buf.st_uid);
// 显示组名
group_name(buf.st_gid);
// 显示字节数
printf("  %lu",buf.st_size);
// 显示最后修改时间
show_time(buf.st_mtime);
// 显示文件名
printf("  %s\n",path);
}

int main(int argc,const char* argv[])
{
list_file_stat("dup.c");
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: