实现ls-l命令

  • Post author:
  • Post category:其他


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;
}



版权声明:本文为taifyang原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。