编程实现ls -l

使用指令ls -l

编译ll.c  并运行

 

需要的头文件,通过man命令查阅即可 

 

#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
#include <pwd.h>
#include <time.h>
#include <dirent.h>
#include <grp.h>
void month(int month)
{
	if(month < 0 || month > 11)
	{
		printf("error");
		return ;
	}
	switch(month)
	{
		case 0:
			printf("jan");
			break;
		case 1:
			printf("feb");
			break;
		case 2:
			printf("mar");
			break;
		case 3:
			printf("apr");
			break;
		case 4:
			printf("may");
			break;
		case 5:
			printf("jun");
			break;
		case 6:
			printf("jul");
			break;
		case 7:
			printf("aug");
			break;
		case 8:
			printf("sep");
			break;
		case 9:
			printf("oct");
			break;
		case 10:
			printf("nov");
			break;
		case 11:
			printf("dec");
			break;
	}
}
	
int main(int argc, char *argv[])
{	
	if(argc < 2)
	{
		printf("input error");
		return -1;
	}
	
	
	DIR *dir = opendir(argv[1]);
	
	if(dir == NULL)
	{
	printf("open error");
	return -1;
	}
	struct dirent *dt;
	while(dt = readdir(dir))
	{
		if(dt->d_name[0] == '.') 
			continue;
		struct stat statbuf;
		if(-1 == lstat(dt->d_name, &statbuf)){
			perror("stat");
			return -1;
		}

		switch(statbuf.st_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;
		}

		int n = 8;
		while(n-->=0)
		{
			if(statbuf.st_mode & 1 << n)
			{
				switch(n%3)
				{
					case 2:
						printf("r");
						break;
					case 1:
						printf("r");
						break;
					case 0:
						printf("x");
						break;
				}
			}else
			{
				printf("-");
			}
		}
		printf(" %ld",statbuf.st_nlink);
	
		printf(" %s ",getpwuid(statbuf.st_uid)->pw_name);
		printf(" %s ",getgrgid(statbuf.st_gid)->gr_name);
	
		printf(" %5ld ",statbuf.st_size);
	
		struct tm *tp = localtime(&statbuf.st_mtime);
	
		month(tp->tm_mon);
		printf("  %2d %2d:%2d",tp->tm_mday,tp->tm_hour,tp->tm_min);
		printf(" %s\n",dt->d_name);
	}
	closedir(dir);
	return 0;

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值