linux下实现ls -l命令

系统:任意的liunx系统

myls.c文件如下:

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


char get_type(mode_t s)
{
    /* switch(s & S_IFMT)
    {
    case S_IFSOCK: return 's';
    case S_IFREG: return '-';
    case S_IFDIR: return 'd';
    case S_IFLNK: return 'l';
    case S_IFIFO: return 'p';
    case S_IFCHR: return 'c';
    case S_IFBLK: return 'b';
    }
    */
    if(S_ISREG(s))return '-';
    if(S_ISLNK(s))return 'l';
    if(S_ISCHR(s))return 'c';
    if(S_ISBLK(s))return 'b';
    if(S_ISSOCK(s))return 's';
    if(S_ISFIFO(s))return 'p';
    if(S_ISDIR(s))return 'd';
}


char *get_per(mode_t s)
{
    static char buf[10] = {0};
    int i = 9;
    while(i--)
    {
        buf[i] = '-';
        if(s & 1<<(8-i) )
        {
            switch(i%3)
            {
                case 0: buf[i] = 'r';break;
                case 1: buf[i] = 'w';break;
                case 2: buf[i] = 'x';break;
            }
        }
    }
return buf;
}


char *get_owner(uid_t uid)
{
    return getpwuid(uid)->pw_name;
}


char *get_gro(gid_t gid)
{
    return getgrgid(gid)->gr_name;
}


char *get_time(time_t t)
{
    static char buf[100];
    strncpy(buf, ctime(&t), 24);
    return buf;
}


int main()
{
    DIR *dp = opendir(".");
    int sum = 0;
    struct stat s;
    struct dirent *p;
    while( p = readdir(dp) )
    {
        stat(p->d_name, &s);
        printf("%c%s %3d %s %s %8ld %s %s\n",
        get_type(s.st_mode),
        get_per(s.st_mode),
        s.st_nlink,
        get_owner(s.st_uid),
        get_gro(s.st_gid),
        s.st_size,
        get_time(s.st_ctime),
        p->d_name);
        sum += s.st_size;
    }   
    printf("total size(k): %d\n", sum/1024);
    // printf( "\033[1;31;40m asdfasdfasdfasdf asdfa sdfa sda\033[0m" );
}

这里写图片描述

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值