ls-l的实现

#include <stdio.h>

#include <unistd.h>

#include <sys/stat.h>

#include <sys/types.h>

#include <stdlib.h>

#include <pwd.h>

#include <grp.h>

#include <time.h>

#include <string.h>

//模拟实现ls -l

//-rw-rw-r-- 1 nowcoder nowcoder 12 12月 3 12:48 a.txt



int main(int argc, char *argv[])

{

    if(argc < 2)

    {

        printf("%s filename\n", argv[0]);

        return -1;

    }



    //  使用stat接受文件的信息

    struct stat st;

    int ret = stat(argv[1], &st);

    if(ret < 0)

    {

        perror("stat");

        return -1;

    }



    char buf[11] = {0};



    switch(st.st_mode&S_IFMT)

    {

        case S_IFSOCK:

            buf[0] = 's';

            break;

        case S_IFDIR:

            buf[0] = 'd';        

            break;  

        case S_IFCHR:

            buf[0] = 'c';

            break;

        case S_IFLNK:

            buf[0] = 'l';

            break;

        case S_IFIFO:

            buf[0] = 'p';  //注意管道文件显示p

            break;  

        case S_IFMT:

            buf[0] = 'm';

            break;    

        case S_IFREG:

            buf[0] = '-';        

            break;  

        case S_IFBLK:

            buf[0] = 'b';

            break;  

        default:

            buf[0] = '?';

            break;

    }




    //  判断文件的访问权限



    //判断文件的所有者

    buf[1] = (st.st_mode & S_IRUSR) ? 'r': '-';

    buf[2] = (st.st_mode & S_IWUSR) ? 'w': '-';

    buf[3] = (st.st_mode & S_IXUSR) ? 'x': '-';



    //判断文件的组

    buf[4] = (st.st_mode & S_IRGRP) ? 'r': '-';

    buf[5] = (st.st_mode & S_IWGRP) ? 'w': '-';

    buf[6] = (st.st_mode & S_IXGRP) ? 'x': '-';



    //判断文件的其他

    buf[7] = (st.st_mode & S_IROTH) ? 'r': '-';

    buf[8] = (st.st_mode & S_IWOTH) ? 'w': '-';

    buf[9] = (st.st_mode & S_IXOTH) ? 'x': '-';



    //硬连接数

    int linknum = st.st_nlink;



    //文件的所有者

    //st结构体里面只有文件的所有者的id

    char *fileuser = getpwuid(st.st_uid)->pw_name;



    //文件所在的组

    char *fliegroup = getgrgid(st.st_gid)->gr_name;



    //文件的大小

    long int filesize = st.st_size;



    //获取修改时间,获取的时间实际上是秒数,从1980年开始

    char *time = ctime(&st.st_mtime);



    char temp[50] ={0};

    strncpy(temp, time, strlen(time)-1);



    char buflong[1024];

    sprintf(buflong, "%s %d %s %s %ld %s %s", buf, linknum, fileuser, fliegroup, filesize, temp, argv[1]);



    printf("%s\n", buflong);

    return 0;

}

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值