编程实现 ls -l 命令所实现的功能

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


char mode[10];/*声明一个存储权限的字符数组*/
void mode_info_my(mode_t st_mode,char *mode);/*函数声明*/
/*函数功能:按linux系统中ls -l命令格式,输出文件或者目录的信息*/
void my_stat(char *p)
{
	char *time;
	int t;
	struct stat st_p;
	if(stat(p,&st_p) == -1)
		printf("stat error\n");
	mode_info_my(st_p.st_mode,mode);
	printf("%s",mode);
	printf(" %ld",(long)st_p.st_nlink);
	printf(" %s",getpwuid(st_p.st_uid)->pw_name);
	printf(" %s",getgrgid(st_p.st_gid)->gr_name);
	printf(" %ld",(long)st_p.st_size);
	time=ctime(&st_p.st_ctime);
	t=strlen(time);
	time[t-1]='\0';
	printf(" %s",time);
}
/*函数功能:获取文件或者目录的权限信息*/
void mode_info_my(mode_t st_mode,char *mode)
{


	if(S_ISREG(st_mode))
		mode[0]='-';
	if(S_ISDIR(st_mode))
		mode[0]='d';
	if(S_ISCHR(st_mode))
		mode[0]='c';
	if(S_ISBLK(st_mode))
		mode[0]='b';


	if(st_mode & S_IRUSR)
		mode[1]='r';
	else
		mode[1]='-';
	
	if(st_mode & S_IWUSR)
		mode[2]='w';
	else
		mode[2]='-';
	if(st_mode & S_IXUSR)
		mode[3]='x';
	else
		mode[3]='-';


	if(st_mode & S_IRGRP)
		mode[4]='r';
	else
		mode[4]='-';
	if(st_mode & S_IWGRP)
		mode[5]='w';
	else
		mode[5]='-';
	if(st_mode & S_IXGRP)
		mode[6]='x';
	else
		mode[6]='-';


	if(st_mode & S_IROTH)
		mode[7]='r';
	else
		mode[7]='-';
	if(st_mode & S_IWOTH)
		mode[8]='w';
	else
		mode[8]='-';
	if(st_mode & S_IXOTH)
		mode[9]='x';
	else
		mode[9]='-';
}



/*主函数*/
int main(int argc,char *argv[])
{


	struct stat st;
	struct dirent *dp;
	DIR *c;	
	char p[256];
	char *dir=NULL;
	if(argc == 1){	/*命令行只有一个参数情况,默认显示当前路径信息*/
		argv[1]=".";
	}
	if(argc>2){
		printf("command error\n");
		return 1;
	}
	if(stat(argv[1],&st) != 0){
		printf("fail to get stat of file\n");
		return -1;
	}


	mode_info_my(st.st_mode,mode);


	if(mode[0] == 'd'){	/*路径为目录的相应操作*/
		if((c=opendir(argv[1]))==NULL){		/*判断路径是否存在*/
			printf("path is empty\n");
			return -1;
		}
		if(chdir(argv[1])!=-1){		/*切换到所给路径*/
			dir=getcwd(dir,0);
		}
		my_stat(dir);	/*输出目录信息*/
		while((dp=readdir(c)) != NULL){		/*遍历目录下的文件和目录,并输出其信息*/
			strcpy(p,argv[1]);
			strcat(p,"/");
			strcat(p,dp->d_name);	/*文件路径连接*/
			my_stat(p);	/*打印信息*/
			printf(" %s\n",dp->d_name);/*输出文件名*/
		}
	}


	else	/*参数是文件,输出文件信息*/
		my_stat(argv[1]);


	return 0;
}


  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值