linux中ls对应函数,linux 中ls命令函数

#include

#include

#include

#include

#include

#include

#include

#include

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;

}

原文:http://www.cnblogs.com/guangliang/p/4358320.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值