linux 中ls命令函数

时间:2021-03-10 19:39:20

#include<stdio.h>
#include<sys/types.h>
#include<sys/stat.h>
#include<dirent.h>
#include<string.h>
#include<sys/types.h>
#include<pwd.h>
#include<grp.h>
void mode_to_letters(int mode,char str[]);
void do_ls(char dirname[]);
void show_stat_info(char *fname,struct stat *buf);
char *uid_to_name(uid_t uid);
char *gid_to_name(gid_t gid);
int main(int ac,char *av[])
{
   if(ac==1)
      do_ls(".");
   else
        while(ac--)
         {
         printf("%s:\n",*++av);
         do_ls(*av);
         }
}
void do_ls(char dirname[])
{
   DIR *drip;                //the directory
   struct dirent *direntp;   //each entry
   struct stat info;

   if((drip=opendir(dirname))==NULL)
        fprintf(stderr,"ls2:cannot open %s\n",dirname);
   else
       {
        while((direntp=readdir(drip))!=NULL)
            if(stat(direntp->d_name,&info)!=-1)
         {
            show_stat_info(direntp->d_name,&info);
        }
            else
        perror(direntp->d_name);
        closedir(drip);
        }
}
void show_stat_info(char *fname,struct stat *buf)
{
   char str[11];
   mode_to_letters(buf->st_mode,str);
   printf("%10s",str);
   //printf("   mode:%o ",buf->st_mode);
   printf("%3d  ",buf->st_nlink);
   printf("%-6s",uid_to_name(buf->st_uid));
   printf("%-7s",gid_to_name(buf->st_gid));
   printf("%8ld ",buf->st_size);
   printf("%12.12s   ",4+ctime(&(buf->st_mtime)));
   printf("%s\n",fname);
}
/*
* This function takes a mode value and a char array
* and puts into the char array the file type and the
* nine letters that correspond to the bits in mode.
* NOTE:It doesn't code setuid,setgid,and sticky
* codes
*/
void mode_to_letters(int mode,char str[])
{
   strcpy(str,"----------");       /*default=no perms*/
  
   if(S_ISDIR(mode)) str[0]='d';    /*directory*/
   if(S_ISCHR(mode)) str[0]='c';    /*char device*/
   if(S_ISBLK(mode)) str[0]='b';    /*block device*/
   if(S_ISREG(mode)) str[0]='-';    /*regular device*/
   
   if(mode & S_IRUSR) str[1]='r';  /*the privilege of the owner*/
   if(mode & S_IWUSR) str[2]='w';
   if(mode & S_IXUSR) str[3]='x';

   if(mode & S_IRGRP) str[4]='r';   /*the privilege of the group*/
   if(mode & S_IWGRP) str[5]='w';
   if(mode & S_IXGRP) str[6]='x';
  
   if(mode & S_IROTH) str[7]='r';   /*the privilege of others*/
   if(mode & S_IWOTH) str[8]='w';
   if(mode & S_IXOTH) str[9]='x';
}
/*transit user id to user name*/
char *uid_to_name(uid_t uid)
{
    struct passwd *getpwuid(),*ptr;
    static char numstr[10];
    if((ptr=getpwuid(uid))==NULL)
       {
    sprintf(numstr,"%d",uid);
       return numstr;
       }
       else
         return ptr->pw_name;
}
/*transit gruop id to group name*/
char *gid_to_name(gid_t gid)
{
    struct group *getgrgid(),*grd_ptr;
    static char numstr[10];
   
    if((grd_ptr=getgrgid(gid))==NULL)
       {
        sprintf(numstr,"%d",gid);
    return numstr;
       }
       else
     return grd_ptr->gr_name;
}