C 语言实现shell里的ls命令

#include <stdio.h>
#include <time.h>
#include <stdlib.h>
#include <errno.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
#include <dirent.h>
#include <string.h>
int main(int argc,char *argv[])
{
	DIR *dir;
	struct dirent *dp;
	int n;
	int i;
	char s[30];
	struct tm *ts;
	struct stat p;
	void ls(char *);
	if(argc!=2)
	{
	printf("Put one filename!\n");	exit(1);
	}

	n=stat(argv[1],&p);
	if(n<0)
	{
	printf("%s\n",strerror(errno));	exit(1);
	}
	

	n=p.st_mode&(017<<12);
	switch (n)
	{
		case 0100000:ls(argv[1]);break;
		case 0040000:{
				if((dir=opendir(argv[1]))==NULL)
				{
					printf("%s\n",strerror(errno));exit(1);
				}
				
				while((dp=readdir(dir))!=NULL)
			{
			//	strcpy(s,"../");
				strcpy(s,argv[1]);
                                strcat(s,"/");
                                strcat(s,dp->d_name);
				ls(s);
			}
			} break;
		default:printf("Error:shoud input a file or a directory!\n"); break;
	}
}
void ls(char *name)	
{	
	int n,i;
	struct tm *ts;
	struct stat p;
	
	n=stat(name,&p);
	if(n<0)
	{
	printf("%s\n",strerror(errno));	exit(1);
	}
/* file type*/
	n=p.st_mode&(017<<12);	
	switch (n)
	{
		case 0140000:printf("s");break;
		case 0120000:printf("l");break;
		case 0100000:printf("-");break;
		case 0060000:printf("b");break;
		case 0040000:printf("d");break;
		case 0020000:printf("c");break;
		case 0010000:printf("p");break;
	}
	
	for(i=0,n=8;i<3;i++)
	{
		
		if(p.st_mode&(01<<n--))
		printf("r");
		else
		printf("-");

		if(p.st_mode&(01<<n--))
		printf("w");
		else
		printf("-");

		if(p.st_mode&(01<<n--))
		printf("x");
		else
		printf("-");
		
	}
/*
	n=p.st_mode&(01<<8);
	if(n==0400)
	printf("r");
	else
	printf("-");	

	 n=p.st_mode&(01<<7);
	if(n==0200)
	printf("w");
	else
	printf("-");	
	n=p.st_mode&(01<<6);
	if(n==0100)
	printf("x");
	else
	printf("-");
*/	
/*number of hard link*/
	printf("%4d",p.st_nlink);
/*user ID of owner*/
	printf("%9d",p.st_uid);
/*group ID of owner*/
	printf("%9d",p.st_gid);
	
/*size of the file*/
	printf("  %d",p.st_size);	
/*time of last modification*/
	ts=localtime(&p.st_mtime);
	printf("  %4d-%2d-%2d  %2d:%2d:%2d\n",ts->tm_year+1900,ts->tm_mon+1,ts->tm_mday,ts->tm_hour,ts->tm_min,ts->tm_sec);
}



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值