文件IO——用c语言编程实现“ls -l 文件名”功能

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

getpwuid

getgrgid

localtime或ctime

ctime函数在C库中,头文件为<time.h>

函数原型:

char *ctime (const time_t *__timer)

作用:返回一个表示当地时间的字符串,当地时间是基于参数 timer

文章中的有些参数,需要自己用man函数自己查阅才能明白,比如switch函数

["code:c"]
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
#include <stdio.h>
#include <pwd.h>
#include <grp.h>
#include <time.h>

int main(int argc, char const *argv[])
{
    struct stat st;
    if (stat(argv[1], &st) < 0)
    {
        perror("stat err");
        return -1;
    }

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

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

    //判断文件权限
    //个人权限
    if (st.st_mode & S_IRUSR)
        printf("r");
    else
        printf("-");
    if (st.st_mode & S_IWUSR)
        printf("w");
    else
        printf("-");
    if ((st.st_mode & S_IXUSR))
        printf("x");
    else
        printf("-");
    
    //小组权限
    if (st.st_mode & S_IRGRP)
        printf("r");
    else
        printf("-");
    if (st.st_mode & S_IWGRP)
        printf("w");
    else
        printf("-");
    if ((st.st_mode & S_IXGRP))
        printf("x");
    else
        printf("-");
    //其他人权限
    if (st.st_mode & S_IROTH)
        printf("r");
    else
        printf("-");
    if (st.st_mode & S_IWOTH)
        printf("w");
    else
        printf("-");
    if ((st.st_mode & S_IXOTH))
        printf("x");
    else
        printf("-");

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

    //用户名 getpwuid()
    printf(" %s", getpwuid(st.st_uid)->pw_name);

    //组名 getgrgid()
    printf(" %s", getgrgid(st.st_gid)->gr_name);

    //文件大小
    printf(" %ld", st.st_size);

    //最后修改的时间 ctime()
    printf(" %.12s", ctime(&st.st_mtime) + 4);//+4:偏移4地址跳过前4位,.12:只打印12个字符

    //名字:
    printf(" %s\n", argv[1]);

    return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值