C语言实现Linux中的ls -l命令源码

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

void function(struct stat*statbuf)
{
	int n = 8;
	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;
	}
	while(n >= 0)
	{
		if(statbuf->st_mode & 1 << n){  //1 0000 0000
			switch(n % 3){
				case 2:
					printf("r");
					break;
				case 1:
					printf("w");
					break;
				case 0:
					printf("x");
					break;
			}
		}else{
			printf("-");
		}
		n--;
	}
	printf("  ");
}
int main(int argc, char *argv[])
{	
	struct stat* buff=(struct stat*)malloc(sizeof(struct stat));
	struct tm* t;
	struct passwd* ursname,*groupname;
	ursname=(struct passwd*)malloc(sizeof(struct passwd));
	size_t t0;
	DIR* d1=opendir("./");
	if(d1==NULL) perror("open");
	struct dirent*dir=readdir(d1);
	while(dir!=NULL)
	{
		if(dir->d_name[0]!='.')
		{
			
			stat(dir->d_name,buff);
			t0=buff->st_mtime;
			function(buff);
			t=localtime(&t0);
			ursname=getpwuid(buff->st_uid);
			groupname=getpwuid(buff->st_gid);
			if(t->tm_hour/10==0&&t->tm_min/10!=0)
			{
				fprintf(stdout,"%ld\t%s\t%s\t%ld\t%d\t%d\t0%d:%d\t%-s\n",
						buff->st_nlink,
						ursname->pw_name,
						groupname->pw_name,
						buff->st_size,
						t->tm_mon+1,
						t->tm_mday,
						t->tm_hour,
						t->tm_min,
						dir->d_name);
			}
			else if(t->tm_min/10==0&&t->tm_hour/10!=0)
			{
				fprintf(stdout,"%ld\t%s\t%s\t%ld\t%d\t%d\t%d:0%d\t%-s\n",
						buff->st_nlink,
						ursname->pw_name,
						groupname->pw_name,
						buff->st_size,
						t->tm_mon+1,
						t->tm_mday,
						t->tm_hour,
						t->tm_min,
						dir->d_name);
			}
			else if(t->tm_hour/10==0&&t->tm_min/10==0)
			{	
				fprintf(stdout,"%ld\t%s\t%s\t%ld\t%d\t%d\t0%d:0%d\t%-s\n",
					buff->st_nlink,
					ursname->pw_name,
					groupname->pw_name,
					buff->st_size,
					t->tm_mon+1,
					t->tm_mday,
					t->tm_hour,
					t->tm_min,
					dir->d_name);
			}
			else
			{
				fprintf(stdout,"%ld\t%s\t%s\t%ld\t%d\t%d\t%d:%d\t%-s\n",
					buff->st_nlink,
					ursname->pw_name,
					groupname->pw_name,
					buff->st_size,
					t->tm_mon+1,
					t->tm_mday,
					t->tm_hour,
					t->tm_min,
					dir->d_name);
			}
			dir=readdir(d1);
		}else
		{
			dir=readdir(d1);
		}
	}
	closedir(d1);
	return 0;
}

运行结果:

 ls -l结果:

        

评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值