您的位置:首页 > 其它

一个类ls函数

2016-02-14 19:55 316 查看
#include <stdio.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <dirent.h>
#include <string.h>
#include <pwd.h>
#include <time.h>
#include <grp.h>

void showls(struct stat *p,char * d_name)
{
char flag;
if(S_ISREG(p->st_mode))flag='-';
else if(S_ISDIR(p->st_mode))flag='d';
else if(S_ISCHR(p->st_mode))flag='c';
else if(S_ISBLK(p->st_mode))flag='b';
else if(S_ISSOCK(p->st_mode))flag='s';
else if(S_ISFIFO(p->st_mode))flag='P';
else if(S_ISLNK(p->st_mode))flag='l';
else flag='?';
printf("%c\t",flag);

//printf("%o\t",p->st_mode&0777);
const char* rwx="rwx";
int i;
for(i=0;i<9;i++)
printf("%c",p->st_mode&0400?rwx[i%3]:'-');
printf("\t");

printf("%2ld\t",p->st_nlink);

struct passwd *s;
s=getpwuid(p->st_uid);
printf("%7s\t",s->pw_name);

printf("%7s\t",getgrgid(p->st_gid)->gr_name);

printf("%ld\t",p->st_size);

char buf[100];
time_t t=p->st_mtime;
strftime(buf,sizeof(buf),"%F %T",localtime(&t));
printf("%s\t",buf);

printf("%s\t",d_name);
printf("\n");
}

int main(int argc,char* argv[])
{
char* path;
if(argc==1)
{
path=".";
}

if(argc==2&&strcmp(argv[1],"-l")==0)
{
path=".";
}

else if(argc==2)
{
path=argv[1];
}

if(argc==3)
{
path=argv[2];
}

if(argc>=2&&strcmp(argv[1],"-l")==0)
printf("类型\t权限\t\t链接数\t用户名\t组\t字节数\t最后一次修改时间\t文件名\n");
if(opendir(path)==NULL)
{//检查是否有这个目录
printf("文件打开失败!请正确输入!\n");
printf("%m");
return -1;
}
DIR *p = opendir(path);//指针指向当前路径的所有内容
if(chdir(path)!=0)
{//设置 path 作为当前工作目录
perror("错误");
return -1;
}
struct dirent *q;//结构体划分内容块
while((q=readdir(p))!=NULL)
{//从工作目录读取
if(q->d_name[0]=='.')
continue;//不显示隐藏文件

if(argc>=2&&strcmp(argv[1],"-l")==0)
{
struct stat s;
stat(q->d_name,&s);
showls(&s,q->d_name);
}
if(argc==1)
printf("%s\t",q->d_name);
}
printf("\n");
closedir(p);
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: