基本实现了Linux下的ls -l命令,对于不同的文件显示不同的颜色和显示符号链接暂时没有实现:
1 /************************************************************************* 2 > File Name: dirwalk.c 3 > Author: 4 > Mail: 5 > Created Time: Tue 31 Mar 2015 11:56:38 AM CST 6 ************************************************************************/ 7 8 #include<stdio.h> 9 #include <sys/types.h> 10 #include <sys/stat.h> 11 #include <fcntl.h> 12 #include <unistd.h> 13 #include <stdlib.h> 14 #include <string.h> 15 #include <dirent.h> 16 #include <time.h> 17 18 #define MAX_PATH 1024 19 #define MODE_LEN 10 20 #define TIME_LEN 20 21 #define NAME_LEN 30 22 23 unsigned long ugo_mode[9] = {S_IRUSR, S_IWUSR, S_IXUSR, S_IRGRP, S_IWGRP, S_IXGRP, S_IROTH, S_IWOTH, S_IXOTH}; 24 char* rwx[3] = {"r", "w", "x"}; 25 char* userpath = "/etc/passwd"; 26 char* grouppath = "/etc/group"; 27 28 /*dirwalk: apply fcn to all files in dir */ 29 void dirwalk(char* dir, void(*fcn)(char*)) 30 { 31 struct dirent *dp; 32 DIR* dfd; 33 34 char name[MAX_PATH]; 35 if((dfd = opendir(dir)) == NULL) 36 { 37 fprintf(stderr, "dirwalk: can't open %s ", dir); 38 return; 39 } 40 41 while((dp = readdir(dfd)) != NULL) 42 { 43 if(strcmp(dp->d_name, ".") == 0 || strcmp(dp->d_name, "..") == 0) 44 { 45 continue; 46 } 47 48 if(strlen(dir) + strlen(dp->d_name) + 2 > sizeof(name)) 49 { 50 fprintf(stderr, "%s/%s too long ", dir, dp->d_name); 51 }else 52 { 53 sprintf(name, "%s/%s", dir, dp->d_name); 54 (*fcn)(name); 55 } 56 } 57 closedir(dfd); 58 } 59 60 /*getname: get the name of the user and the name of the group name */ 61 void getname(char* path, int id, char* name) 62 { 63 64 int fd, save_fd; 65 if((fd = open(path, O_RDONLY)) < 0) 66 { 67 perror("open "); 68 exit(1); 69 } 70 71 save_fd = dup(STDIN_FILENO); 72 dup2(fd, STDIN_FILENO); 73 close(fd); 74 char p[MAX_PATH]; 75 char usrid[20]; 76 sprintf(usrid, "%d", id); 77 char* puid; 78 while((scanf("%s", p)) != EOF) 79 { 80 if((puid = strstr(p, usrid)) != NULL) 81 { 82 char* pFlag; 83 char* pResult; 84 if((pFlag = strstr(p, ":")) != NULL) 85 { 86 pResult = pFlag; 87 pFlag = strstr(pFlag + 1, ":"); 88 } 89 if(pFlag != NULL) 90 { 91 if((memcmp(pFlag + 1, puid, strlen(usrid))) == 0) 92 { 93 *pResult = '