用stat 写出ls -l的全功能

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

void mode(struct stat buf);
void usrm(struct stat buf);
void grpm(struct stat buf);
void othm(struct stat buf);
void name(struct stat buf);

int main(int argc, const char *argv[])
{
	struct stat buf;
	int i;
	i = stat(argv[1],&buf);
	if(i != 0)
	{
		perror("fail to stat\n");
		exit(1);
	}
	mode(buf);
	usrm(buf);
	grpm(buf);
	othm(buf);
	printf(" %d ",buf.st_nlink);
	name(buf);
	printf("%ld ",buf.st_size);
	printf("%.12s ",ctime(&buf.st_mtime)+4);
	printf("%s\n",argv[1]);
	return 0;
}
void mode(struct stat buf)
{
	if(S_ISREG(buf.st_mode))
		putchar('-');
	else if(S_ISDIR(buf.st_mode))
		putchar('d');
	else if(S_ISCHR(buf.st_mode))
		putchar('c');
	else if(S_ISBLK(buf.st_mode))
		putchar('b');
	else if(S_ISFIFO(buf.st_mode))
		putchar('p');
	else if(S_ISLNK(buf.st_mode))
		putchar('l');
	else if(S_ISSOCK(buf.st_mode))
		putchar('s');
}
void usrm(struct stat buf)
{
	if(buf.st_mode & S_IRUSR)
		putchar('r');
	else
		putchar('-');
	if(buf.st_mode & S_IWUSR)
		putchar('w');
	else
		putchar('-');
	if(buf.st_mode & S_IXUSR)
		putchar('x');
	else
		putchar('-');
}
void grpm(struct stat buf)
{
	if(buf.st_mode & S_IRGRP)
		putchar('r');
	else
		putchar('-');
	if(buf.st_mode & S_IWGRP)
		putchar('w');
	else
		putchar('-');
	if(buf.st_mode & S_IXGRP)
		putchar('x');
	else
		putchar('-');
}
void othm(struct stat buf)
{
	if(buf.st_mode & S_IROTH)
		putchar('r');
	else
		putchar('-');
	if(buf.st_mode & S_IWOTH)
		putchar('w');
	else
		putchar('-');
	if(buf.st_mode & S_IXOTH)
		putchar('x');
	else
		putchar('-');
}
void name(struct stat buf)
{
	struct passwd *p; 
 	struct group *g;
	p = getpwuid(buf.st_uid);
	g = getgrgid(buf.st_gid);
	printf("%s %s ",p->pw_name,g->gr_name);
}

  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值