📄 ls.c
字号:
/*实现ls -l -a*/#include <unistd.h>#include <stdio.h>#include <dirent.h>#include <time.h>#include <string.h>#include <sys/stat.h>#include <stdlib.h>#include <pwd.h>#include <grp.h>/*获取用户名*/char *uid_to_name(uid_t uid){ struct passwd *pw_ptr; static char numstr[10]; if( (pw_ptr = getpwuid(uid)) == NULL) { printf(numstr, "%d", uid); return numstr; } else return pw_ptr->pw_name;}/*获取用户组名*/char *gid_to_name(gid_t gid){ struct group *grp_ptr; static char numstr[10]; if ((grp_ptr = getgrgid(gid)) == NULL) { sprintf(numstr, "%d", gid); return numstr; } else return grp_ptr->gr_name;}/*获取文件夹或文件的权限*/int get_purview(int mode,char *purview){ strcpy(purview, "----------"); if(S_ISDIR(mode)) purview[0] = 'd'; if(S_ISCHR(mode)) purview[0] = 'c'; if(S_ISBLK(mode)) purview[0] = 'b'; if(mode & S_IRUSR) purview[1] = 'r'; if(mode & S_IWUSR) purview[2] = 'w'; if(mode & S_IXUSR) purview[3] = 'x'; if(mode & S_IRGRP) purview[4] = 'r'; if(mode & S_IWGRP) purview[5] = 'w'; if(mode & S_IXGRP) purview[6] = 'x'; if(mode & S_IROTH) purview[7] = 'r'; if(mode & S_IWOTH) purview[8] = 'w'; if(mode & S_IXOTH) purview[9] = 'x'; }/*显示ls -l的内容*/int show_ls(char *filename,struct stat *statbuf){ char purview[11] = {0}; get_purview(statbuf->st_mode,purview); printf("%s",purview);//文件权限 printf("%5d ",statbuf->st_nlink);//文件的硬链接数目 printf("%-8s",uid_to_name(statbuf->st_uid));//文件拥有者的名称 printf("%-8s",gid_to_name(statbuf->st_gid));//文件的组名称 printf("%8ld ",(long)statbuf->st_size);//文件的大小 printf("%.12s ",4+ctime(&statbuf->st_mtime));//文件的修改时间 printf("%s\n", filename);//文件名}/*读取目录*/void printdir(char *dir){ DIR *dp; struct dirent *entry; struct stat statbuf; char buf[1024];//存放当前路径 if (getcwd(buf,sizeof(buf)) == NULL) { exit(1); } if ((dp = opendir(dir)) == NULL) { fprintf(stderr,"can not open directory: %s\n",dir); return ; } chdir(dir); while ((entry = readdir(dp)) != NULL) { lstat(entry->d_name,&statbuf); if (strcmp(".",entry->d_name) == 0 || strcmp("..",entry->d_name) == 0 || entry->d_name[0] == '.') continue; show_ls(entry->d_name,&statbuf); } chdir(buf);//还原路径 closedir(dp);}/*主函数*/int main(int argc,char *argv[]){ int i; if (argc == 1) { printdir("."); return 0; } for (i=1; i<argc; i++) { printf("%s:\n",argv[i]); printdir(argv[i]); printf("\n\n"); } return 0;}
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -