实现简单的 ls 命令

今天天气不错,实现个自己的 ls 命令玩玩,现在实现来 -l 参数,以后有空再把其他参数补全:)

 

  1 #include <stdio.h>
  2 #include <sys/types.h>
  3 #include <sys/stat.h>
  4 #include <dirent.h>
  5 #include <string.h>
  6 #include <pwd.h>
  7 #include <time.h>
  8 #include <grp.h>
  9 
 10 void showls(struct stat *p,char * d_name)
 11 {
 12     char flag;
 13     if(S_ISREG(p->st_mode))flag='-';
 14     else if(S_ISDIR(p->st_mode))flag='d';
 15         else if(S_ISCHR(p->st_mode))flag='c';
 16         else if(S_ISBLK(p->st_mode))flag='b';
 17     else if(S_ISSOCK(p->st_mode))flag='s';
 18         else if(S_ISFIFO(p->st_mode))flag='P';
 19         else if(S_ISLNK(p->st_mode))flag='l';                     
 20     else flag='?';
 21     printf("%c\t",flag);
 22 
 23     //printf("%o\t",p->st_mode&0777);
 24     const char* rwx="rwx";
 25     int i;
 26     for(i=0;i<9;i++)
 27         printf("%c",p->st_mode&0400?rwx[i%3]:'-');
 28     printf("\t");
 29 
 30 
 31     printf("%2d\t",p->st_nlink);
 32 
 33     struct passwd *s;
 34     s=getpwuid(p->st_uid);
 35     printf("%7s\t",s->pw_name);
 36 
 37     printf("%7s\t",getgrgid(p->st_gid)->gr_name);
 38 
 39     printf("%ld\t",p->st_size);
 40 
 41     char buf[100];
 42     time_t t=p->st_mtime;
 43     strftime(buf,sizeof(buf),"%F %T",localtime(&t));
 44     printf("%s\t",buf);
 45 
 46     printf("%s\t",d_name);
 47     printf("\n");
 48 }
 49 
 50 int main(int argc,char* argv[])
 51 {
 52     char* path;
 53     if(argc==1)
 54     {
 55         path=".";
 56     }
 57         
 58     if(argc==2&&strcmp(argv[1],"-l")==0)
 59     {
 60         path=".";
 61     }
 62         
 63     else if(argc==2)
 64     {
 65         path=argv[1];    
 66     }
 67     
 68     if(argc==3)
 69     {
 70         path=argv[2];        
 71     }
 72 
 73     if(argc>=2&&strcmp(argv[1],"-l")==0)
 74         printf("类型\t权限\t\t链接数\t用户名\t组\t字节数\t最后一次修改时间\t文件名\n");
 75     if(opendir(path)==NULL)
 76     {//检查是否有这个目录
 77         printf("文件打开失败!请正确输入!\n");
 78         printf("%m");
 79         return -1;
 80     }
 81     DIR *p = opendir(path);//指针指向当前路径的所有内容
 82     if(chdir(path)!=0)
 83     {//设置 path 作为当前工作目录
 84         perror("错误");
 85         return -1;
 86     }
 87     struct dirent *q;//结构体划分内容块
 88     while((q=readdir(p))!=NULL)
 89     {//从工作目录读取
 90         if(q->d_name[0]=='.')
 91             continue;//不显示隐藏文件
 92         
 93         if(argc>=2&&strcmp(argv[1],"-l")==0)
 94         {
 95             struct stat s;
 96             stat(q->d_name,&s);
 97             showls(&s,q->d_name);
 98         }
 99         if(argc==1)
100             printf("%s\t",q->d_name);
101     }
102     printf("\n");
103     closedir(p);
104     return 0;
105 }

 

执行结果:

posted @ 2015-09-21 01:55  ChessChan  阅读(282)  评论(0编辑  收藏  举报