编程实现“ls -l 文件名“功能

 

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

int main(int argc, char const *argv[])
{
    struct stat s;
    if (stat("ccc.c", &s) < 0)
    {
        perror("stat err");
        return -1;
    }
    printf("%lu\n", s.st_ino);

    printf("%lu\n", s.st_size);

    printf("%#o\n", s.st_mode);
   

    switch (s.st_mode & S_IFMT) //判断文件类型
    {
    case S_IFSOCK:
        printf("s");
        break;
    case S_IFCHR:
        printf("c");
        break;
    case S_IFLNK:
        printf("l");
        break;
    case S_IFREG:
        printf("-");
        break;
    case S_IFBLK:
        printf("b");
        break;
    case S_IFDIR:
        printf("d");
        break;
    case S_IFIFO:
        printf("p");
        break;
    }

    for (int n = 8; n >= 0; n--) //判断文件权限
        if (s.st_mode & (1 << n))
            switch (n % 3)
            {
            case 2:
                printf("r");
                break;
            case 1:
                printf("w");
                break;
            case 0:
                printf("x");
                break;
            }
        else
        {
            printf("-");
        }

    char buf[4]="rwx-";//判断文件权限
    for(int i =0;i<9;i++)
    {
        printf("%c",(s.st_mode& (0400>>i))? buf[i%3]:buf[3])

    }

    printf(" %d", s.st_nlink); //硬链接数

    //用户和组
    struct passwd *p; //用户
    p = getpwuid(s.st_uid);
    printf(" %s", p->pw_name);

    struct group *q; //组
    q = getgrgid(s.st_gid);
    printf(" %s", q->gr_name);

    printf(" %ld", s.st_size); //查看大小

    struct tm *now_time;//最后访问时间
    now_time = localtime(&s.st_mtime);
    printf(" %d-%d-%d %d:%d", now_time->tm_year + 1900,
           now_time->tm_mon + 1,
           now_time->tm_mday, now_time->tm_hour,
           now_time->tm_min);



	printf("%s ","  ccc.c");//打印文件名

    return 0;
}

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值