AI智能
改变未来

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

#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\");}
赞(0) 打赏
未经允许不得转载:爱站程序员基地 » Linux基础:模拟ls -l命令的实现(环境ubutun)