IO day2 文件IO

使用函数实现Linux ls -li 功能

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

int main(int argc, char const *argv[])
{
    if (argc != 2)
    {
        printf("使用格式:%s <file>\n", argv[0]);
        return -1;
    }
    struct stat s;
    if (stat(argv[1], &s) > 0)
    {
        perror("stat err");
        return -1;
    }
    //ino
    printf("%lu ", s.st_ino);
    //文件类型与权限
    //文件类型
    switch (s.st_mode & S_IFMT)
    {
    case S_IFSOCK:
        printf("s");
        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_IFCHR:
        printf("c");
        break;
    case S_IFIFO:
        printf("p");
        break;
    }
    //个人权限
    if (s.st_mode & S_IRUSR)
        putchar('r');
    else
        putchar('-');
    if (s.st_mode & S_IWUSR)
        putchar('w');
    else
        putchar('-');
    if (s.st_mode & S_IXUSR)
        putchar('x');
    else
        putchar('-');
    //组权限
    if (s.st_mode & S_IRGRP)
        putchar('r');
    else
        putchar('-');
    if (s.st_mode & S_IWGRP)
        putchar('w');
    else
        putchar('-');
    if (s.st_mode & S_IXGRP)
        putchar('x');
    else
        putchar('-');
    //其他用户权限
    if (s.st_mode & S_IROTH)
        putchar('r');
    else
        putchar('-');
    if (s.st_mode & S_IWOTH)
        putchar('w');
    else
        putchar('-');
    if (s.st_mode & S_IXOTH)
        printf("x ");
    else
        printf("- ");
    //硬链接数
    printf("%u ", s.st_nlink);
    //用户名
    struct passwd *pr = getpwuid(s.st_uid);
    printf("%s ", pr->pw_name);
    //组名
    struct group *gr = getgrgid(s.st_gid);
    printf("%s ", gr->gr_name);
    //文件大小(总字节数)
    printf("%lu ", s.st_size);
    //时间
    time_t t = s.st_mtime;
    struct tm *time=localtime(&t);
    printf("%d月   %d %d:%d ", time->tm_mon + 1, time->tm_mday, time->tm_hour, time->tm_min);
    printf("%s\n",argv[1]);
    return 0;
}

权限处可进行优化,代码如下: 

   //权限
    char mod[4]="rwx-";
    for(int i=0;i<9;i++)
    {
        printf("%c",(s.st_mode & (0400 >> i))?mod[i%3]:mod[3]);
    }
    putchar(32);

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值