实现Linux命令 ls -l

        在Linux下,ls -l命令可以查看指定路径目录下所有文件的详细信息。如果要用.c文件实现这样一个功能,那么思路可以如下:首先,用main函数的参数argv[ ]数组获取命令行的数量,如果数量大于2,说明除 ls 和 -l 外还有一个参数,那么这里第三个参数就对应是指定的路径,如果是两个参数就把 . 拷入缓冲区,否则就把第三个参数argv[2]拷入缓冲区;那么这个缓冲区肯定是有用的,缓冲区里存着要查看目录的路径,如果路径存在的话,用一个DIR类型的指针接收opendir,获取指定目录流,再用readdir函数进入目录循环读取文件,读取到的文件用d_name获取文件名,连同之前的目录路径一起写入缓冲区,这样文件的路径就完整了,这时候可以把完整路径送进一个打印文件信息的函数,函数里由stat和结构体存放文件的信息并打印出来。

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

int all;

void show_file(const char *file)
{
	struct stat buf;
	if(stat(file,&buf)==-1)//获取到当前文件的属性
	{
		perror("stat");
		return;
	}
	all+=(int)buf.st_size;//计算占用总数

	char time_str[100];//存放时间
	struct tm *now=localtime(&buf.st_mtime);//转化成当前时间
	strftime(time_str,sizeof(time_str),"%-1m月\t%d %H:%M",now);//格式和时间信息存入缓冲区
	//格式化打印出所有文件的详细信息,主要依赖stat
	printf("%s",(S_ISDIR(buf.st_mode))?"d":"-");
	printf("%s",(buf.st_mode & S_IRUSR)?"r":"-");
	printf("%s",(buf.st_mode & S_IWUSR)?"w":"-");
	printf("%s",(buf.st_mode & S_IXUSR)?"x":"-");
	printf("%s",(buf.st_mode & S_IRGRP)?"r":"-");
	printf("%s",(buf.st_mode & S_IWGRP)?"w":"-");
	printf("%s",(buf.st_mode & S_IXGRP)?"x":"-");
	printf("%s",(buf.st_mode & S_IROTH)?"r":"-");
	printf("%s",(buf.st_mode & S_IWOTH)?"w":"-");
	printf("%s",(buf.st_mode & S_IXOTH)?"x":"-");
	printf(" %d",(int)buf.st_nlink);//硬链接数
	printf(" %d",(int)buf.st_uid);
	printf(" %d",(int)buf.st_gid);
	printf("\t%d",(int)buf.st_size);
	printf("\t%s %s\n",time_str,file);//打印时间缓冲区
}

int main(int argc,const char* argv[])
{
	char path[1024];//存放要查看的目录路径
	if(argc==2)
		strcpy(path,".");//如果参数只有两个说明未指定目录默认查看当前路径
	else
		strncpy(path,argv[2],sizeof(path-1));
	DIR *dir_path=opendir(path);//获取指定目录流
	struct dirent *dir;
	if(dir_path)
	{
		while((dir=readdir(dir_path))!=NULL)//进到目录下循环读取里面的文件
		{
			char file[1024];//存放指定目录+读取到的文件路径
			snprintf(file,sizeof(file),"%s/%s",path,dir->d_name);//更新路径
			show_file(file);
		}
		closedir(dir_path);
		printf("总用量:%d\n",all);
	}
	else perror("opendir");
		
	return 0;
}

over

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值