Linux ls -l命令 用C语言实现

6 篇文章 0 订阅

要点在于,跟ls -l的显示格式一致

#include<dirent.h>
#include<stdio.h>
#include<sys/types.h>
#include<sys/stat.h>
#include<unistd.h>
#include<pwd.h>
#include<grp.h>
#include<time.h>
#include<string.h>

int main(int argc,char *argv[])
{
    struct tm *tm;
    struct group * grp;
    struct passwd *pwd;
    struct stat sb;
    DIR *d;
    struct dirent * dir;
    char buf[1024];
    ssize_t len;
    // d=opendir(".");
    if(argc>1){
        printf("%s\n\n",argv[1]);
        d=opendir(argv[1]);
    }else{
        d=opendir(".");
    }
    if(d)
    {
        //  printf("d!=null\n");
        while((dir=readdir(d))!=NULL)
        {
        //直接读的话会出现  .   和 ..,要去掉这两个
        if(!strcmp(dir->d_name,".")||!strcmp(dir->d_name,"..")) continue;
        // printf("%s\n",dir->d_name);
        if(lstat(dir->d_name,&sb)!=-1)
        {
            printf( (S_ISDIR(sb.st_mode)) ? "d" : "-");
            printf( (sb.st_mode & S_IRUSR) ? "r" : "-");
            printf( (sb.st_mode & S_IWUSR) ? "w" : "-");
            printf( (sb.st_mode & S_IXUSR) ? "x" : "-");
            printf( (sb.st_mode & S_IRGRP) ? "r" : "-");
            printf( (sb.st_mode & S_IWGRP) ? "w" : "-");
            printf( (sb.st_mode & S_IXGRP) ? "x" : "-");
            printf( (sb.st_mode & S_IROTH) ? "r" : "-");
            printf( (sb.st_mode & S_IWOTH) ? "w" : "-");
            printf( (sb.st_mode & S_IXOTH) ? "x" : "-");
            printf(" %d ",sb.st_nlink);
            pwd=getpwuid(sb.st_uid);
            grp=getgrgid(sb.st_gid);
            //获取文件所属用户名、所属组名,文件大小
            printf("%s %s %d ",pwd->pw_name,grp->gr_name,sb.st_size);
            //根据时间戳获取世间
            tm=localtime(&sb.st_mtime);
            //格式化时间
            printf("%d月 %d %d:%d %s",tm->tm_mon+1,tm->tm_mday,tm->tm_hour,tm->tm_min,basename(dir->d_name));
            //如果是link类型的文件,还得模拟ls -l显示其真实位置!
            if((S_IFMT & sb.st_mode)==S_IFLNK){
                if((len=readlink(dir->d_name,buf,sizeof(buf)-1))!=-1)
                { 
                    buf[len]='\0';}
                    printf("->%s",buf);
                } 
                printf("\n");
            }
        }
        closedir(d);
    }
    return 0;
}

这里写图片描述

  • 2
    点赞
  • 14
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值