Linux 中的文件操作-文件io:模拟ls -l命令。

/*
*功能:模拟ls命令
*/

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

//用stat模拟ls命令
void ls(const char *path)
{
    struct stat st;
    if(stat(path, &st) == -1)
    {
        perror("获取文件失败\n");
        return;
    }

    
    //文件的权限以-rwxr--r--的形式显示,文件拥有者,文件所属组,其他用户的权限都要显示
    char perm[11] = {0};
    sprintf(perm, "%c", (st.st_mode & S_IRUSR)? 'r' : '-');
    sprintf(&perm[1], "%c", (st.st_mode & S_IWUSR)? 'w' : '-');
    sprintf(&perm[2], "%c", (st.st_mode & S_IXUSR)? 'x' : '-');
    sprintf(&perm[3], "%c", (st.st_mode & S_IRGRP)? 'r' : '-');
    sprintf(&perm[4], "%c", (st.st_mode & S_IWGRP)? 'w' : '-');
    sprintf(&perm[5], "%c", (st.st_mode & S_IXGRP)? 'x' : '-');
    sprintf(&perm[6], "%c", (st.st_mode & S_IROTH)? 'r' : '-');
    sprintf(&perm[7], "%c", (st.st_mode & S_IWOTH)? 'w' : '-');
    sprintf(&perm[8], "%c", (st.st_mode & S_IXOTH)? 'x' : '-');

    //打印权限
    printf("-%s ",perm);

    //打印硬链接数
    printf("%lu ", st.st_nlink);

    //打印文件的所有者用户名
    struct passwd *pw = getpwuid(st.st_uid);
    printf("%s ", pw->pw_name);


    //文件所属的用户组
    struct group *gr = getgrgid(st.st_gid);
    printf("%s ", gr->gr_name);

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

    //打印文件修改时间
    struct tm *timeinfo = localtime(&st.st_mtime);
    char timestr[26];
    strftime(timestr, 26, "%Y-%m-%d %H:%M:%S", timeinfo);
    printf("%s ", timestr);

    //打印文件名
    printf("%s\n", path);

}


int main(int argc, char const *argv[])
{
    if(argc != 2)
    {
        printf("参数错误\n");
        return -1;
    }

    ls(argv[1]);

    return 0;
}

打印效果

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值