Linux基础:模拟ls -l命令的实现(环境ubutun)

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

void file_type(mode_t mode)
{
	switch(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;
	}
}

void file_mode(mode_t mode)
{
	printf("%c",mode & S_IRUSR?'r':'-');
	printf("%c",mode & S_IWUSR?'w':'-');
	printf("%c",mode & S_IXUSR?'x':'-');
	printf("%c",mode & S_IRGRP?'r':'-');
	printf("%c",mode & S_IWGRP?'w':'-');
	printf("%c",mode & S_IXGRP?'x':'-');
	printf("%c",mode & S_IROTH?'r':'-');
	printf("%c",mode & S_IWOTH?'w':'-');
	printf("%c",mode & S_IXOTH?'x':'-');
}

void user_name(uid_t uid)
{
	struct passwd* pd =  getpwuid(uid);
	printf("  %s",pd->pw_name);
}

void group_name(gid_t gid)
{
	struct group * gp = getgrgid(gid);
	printf(" %s",gp->gr_name);
}

void show_time(time_t mtime)
{
	struct tm * t = localtime(&mtime);
	printf("  %d月 %d %d:%d",t->tm_mon+1,t->tm_mday,t->tm_hour,t->tm_min);

}

void list_file_stat(const char* path)
{
	// 获取文件属性
	struct stat buf;
	if(stat(path,&buf))
	{
		perror("stat");
		return;
	}

	// 显示文件类型
	file_type(buf.st_mode);
	// 显示文件权限
	file_mode(buf.st_mode);
	// 显示目录层数
	printf("  %c",S_ISDIR(buf.st_mode)?'2':'1');
	// 显示用户名
	user_name(buf.st_uid);
	// 显示组名
	group_name(buf.st_gid);
	// 显示字节数
	printf("  %lu",buf.st_size);
	// 显示最后修改时间
	show_time(buf.st_mtime);
	// 显示文件名
	printf("  %s\n",path);
}

int main(int argc,const char* argv[])
{
	list_file_stat("dup.c");
}

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值