模拟实现ls命令

  1 #include <stdio.h>
  2 #include <string.h>
  3 #include <dirent.h>
  4 #include <errno.h>
  5 #include <sys/stat.h>
  6 #include <unistd.h>
  7 #include <pwd.h>
  8 #include <grp.h>
  9 #include <time.h>
 10 
 11 int main(int argc, char* argv[])
 12 {
 13     if (argc != 2)
 14     {
 15         printf("Usage : ls path
");
 16         return 0;
 17     }
 18 
 19     char path[256] = {0};
 20     strcpy(path, argv[1]);
 21 
 22     int l = strlen(path);
 23     if (path[l - 1] != '/')
 24         path[l] = '/';
 25 
 26     DIR* d = opendir(path);
 27     if (!d)
 28     {
 29         printf("Failed to open path : %s
", strerror(errno));
 30         return 0;
 31     }
 32 
 33     char cp[256];
 34     while (dirent* ent = readdir(d))
 35     {
 36         memset(cp, 0, sizeof(cp));
 37         strcpy(cp, path);
 38         strcat(cp, ent->d_name);
 39 
 40         struct stat s;
 41         stat(cp, &s);
 42 
 43         if (S_ISDIR(s.st_mode))
 44             printf("d");
 45         else if (S_ISCHR(s.st_mode))
 46             printf("c");
 47         else if (S_ISBLK(s.st_mode))
 48             printf("b");
 49         else if (S_ISFIFO(s.st_mode))
 50             printf("c");
 51         else if (S_ISLNK(s.st_mode))
 52             printf("l");
 53         else if (S_ISSOCK(s.st_mode))
 54             printf("c");
 55         else
 56             printf("-");
 57 
 58         if (s.st_mode & S_IRUSR)
 59             printf("r");
 60         else
 61             printf("-");
 62 
 63         if (s.st_mode & S_IWUSR)
 64             printf("w");
 65         else
 66             printf("-");
 67 
 68         if (s.st_mode & S_IXUSR)
 69             printf("x");
 70         else
 71             printf("-");
 72 
 73         if (s.st_mode & S_IRGRP)
 74             printf("r");
 75         else
 76             printf("-");
 77 
 78         if (s.st_mode & S_IWGRP)
 79             printf("w");
 80         else
 81             printf("-");
 82 
 83         if (s.st_mode & S_IXGRP)
 84             printf("x");
 85         else
 86             printf("-");
 87 
 88         if (s.st_mode & S_IROTH)
 89             printf("r");
 90         else
 91             printf("-");
 92 
 93         if (s.st_mode & S_IWOTH)
 94             printf("w");
 95         else
 96             printf("-");
 97 
 98         if (s.st_mode & S_IXOTH)
 99             printf("x");
100         else
101             printf("-");
102 
103         struct passwd* pwd = getpwuid(s.st_uid);
104         struct group* grp = getgrgid(s.st_gid);
105         printf(" %6ld %s %s %10ld %s
", s.st_nlink, pwd->pw_name, grp->gr_name, s.st_size, ent->d_name);
106     }
107     return 0;
108 }
原文地址:https://www.cnblogs.com/nuoforever/p/14037211.html