实现一个终端ls -l 指令

#include <stdio.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <fcntl.h>
#include <string.h>
#include <unistd.h>
#include <pwd.h>
#include <grp.h>
#include <time.h>
//文件属性
void get_getattribut(mode_t m){
	switch(m&S_IFMT){
	case S_IFBLK:printf("b");break;
	case S_IFCHR:printf("c");break;
	case S_IFDIR:printf("d");break;
	case S_IFIFO:printf("p");break;
	case S_IFLNK:printf("l");break;
	case S_IFREG:printf("-");break;
	case S_IFSOCK:printf("s");break;
	default: printf("mode参数错误\n");
	}

}
//文件权限
char* getattribute(mode_t m,char str[10],int num){
	if(num<10){
		return NULL;
	}
	int i;
	char p[]="rwx";
	for(i=0;i<9;i++){
		if(m&(0400>>i)==0){
			putchar('-');
			str[i]=p[i%3];
			continue;
		}
			else{
			printf("%c",p[i%3]);
			str[i]=p[i%3];
		}
		fflush(stdout);
	}
	printf(" ");
	return str;
}
void property_gid(gid_t id){
	struct group* ged=getgrgid(id);
		if(ged==NULL){
			perror("getgrgid");
			return ;
		}
		printf("%s\t",ged->gr_name);
}
void property_uid(uid_t id){
	struct passwd* usd=getpwuid(id);
		if(usd==NULL){
			perror("getpwnam");
			return ;
		}
		printf("%s ",usd->pw_name);
}
void property_time(time_t t){
		
	struct tm* t1=localtime(&t);
	char* p[12];
	p[0]="一月";
	p[1]="二月";
	p[2]="三月";
	p[3]="四月";
	p[4]="五月";
	p[5]="六月";
	p[6]="七月";
	p[7]="八月";
	p[8]="九月";
	p[9]="十月";
	p[10]="十一月";
	p[11]="十二月";
	printf("%s %d %d %d:%d\t",p[t1->tm_mon],\
			t1->tm_mday,t1->tm_hour,t1->tm_min,t1->tm_sec\
		  );
}

int main(int argc, const char *argv[])
{
	if(argc<2){
		printf("请在命令行输入两个参数\n");
	}
	struct stat buf;
	if(stat(argv[1],&buf)<0){
		perror("stat");
		return 0;
	}

	//文件的类型以及其权限
	get_getattribut(buf.st_mode);
	char str[10]=" ";
	char* p;
	p=getattribute(buf.st_mode,str,10);
	if(p==NULL){
		printf("获取文件属性失败\n");
		return 0;
	}
	//文件的硬链接数
	printf("%ld ",buf.st_nlink);
	//文件的所属用户名
	property_uid(buf.st_uid);
	//文件的所属组用户
	property_gid(buf.st_gid);
	//文件的大小
	printf("%ld ",buf.st_size);
	//文件的时间
	property_time((time_t)buf.st_ctime);
	//文件的名字
	printf("%s\n",argv[1]);
	return 0;
}

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值