实现ls-l命令

本文探讨了如何使用lstat函数获取文件属性,并通过getgrgid获取组名,同时解析st_mode、权限和时间戳。通过实例展示了stat与lstat的区别以及在ls_ls.c程序中的应用。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

struct group *getgrgid(gid_t gid); 获得组名
struct group{
char *gr_name; /group name/
char *gr_passwd; /group passwd/
gid_t gr_gid; /group ID/
char **gr_mem; /NULL-terminated array of pointers to names of group members/
};

struct tm *localtime(const time_t *timep);
传入参数timep对应stat函数得到的结构体的秒数(time_t类型)
返回tm结构
struct tm{
int tm sec; /Seconds(0-60)/秒
int tm_min; /Minutes(0-59)/分钟
int tm_hour; /Hours(0-23)/小时
int tm_mday; /Day of the month(1-31)/天
int tm_mon; /Month(0-11)/月,需要+1
int tm_year; /Year-1900/年,需要+1900
int tm_wday; /Day of the week(0-6,Sunday=0)/
int tm_yday; /Day in the year(0-365,1 Jan=0)/
int tm_isdat; /Daylight saving time/

注意stat与lstat的区别,
stat碰到链接,会追溯到源文件(穿透),lstat不会穿透。

ls_ls.c

#include<stdio.h>
#include<sys/type.h>
#include<sys/stat.h>
#include<fcntl.h>
#include<unistd.h>
#include <string.h>
#include <time.h>
#include <pwd.h>
#include <grp.h>

int main(int argc,char *argv[])
{
    if(argc!=2){
        printf("./a.out filename\n");
        return -1;
    }
    //调用stat 得到文件属性信息
    struct stat sb;
    //stat(argv[1],&sb);
    lstat(argv[1],&sb);
    //解析属性信息,st_mode,uid,gid,time
    //st_mode
    char stmode[11]={0};
    memset(stmode,'-',sizeof(stmode)-1);
    if(S_ISREG(sb.st_mode)) stmode[0]='-'; //普通文件
    if(S_ISDIR(sb.st_mode)) stmode[0]='d';
    if(S_ISCHR(sb.st_mode)) stmode[0]='c';
    if(S_ISBLK(sb.st_mode)) stmode[0]='b';
    if(S_ISFIFO(sb.st_mode)) stmode[0]='p';
    if(S_ISSOCK(sb.st_mode)) stmode[0]='s';
    
    //解析权限
    if(sb.st_mode&S_IRUSR) stmode[1]='r';
    if(sb.st_mode&S_IWUSR) stmode[2]='w';
    if(sb.st_mode&S_IXUSR) stmode[3]='x';

    if(sb.st_mode&S_IRUSR) stmode[4]='r';
    if(sb.st_mode&S_IWUSR) stmode[5]='w';
    if(sb.st_mode&S_IXUSR) stmode[6]='x';
 
    if(sb.st_mode&S_IRUSR) stmode[7]='r';
    if(sb.st_mode&S_IWUSR) stmode[8]='w';
    if(sb.st_mode&S_IXUSR) stmode[9]='x';

    //分析 用户名,组名可以通过函数getpwuid,getgrgid获得
    //时间获取
    struct tm *filetm=localtime(&sb.st_atim.tv_sec);
    char timebuff[20]={0};
    sprintf(timebuf,"%d月    %d %d:%d",filetm->tm_mon+1,filetm->tm_day,filetm->tm_hour,filetm->tm_min);

    printf("%s %ld %s %s %ld %s %s\n",stmode,sb.st_nlink,getpwid(sb.st_uid)->pw_name,
getgrgid(sb.st_gid)->gr_name,sb.st_size,timebuf,argv[1]);
    return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

给算法爸爸上香

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值