简单实现Linux中ls功能
#include <sys/types.h>
#include <unistd.h>
#include <fcntl.h>
#include <dirent.h>
#include <stdio.h>
#include <string.h>
#include <limits.h>
#include <sys/stat.h>
/*实现ls功能并显示目录文件和一般文件执行权限文件的颜色显示*/
int main(int c,char** v)
{
char path[256]={"./"};
if(c>=2)
{
strcpy(path,v[1]);//指定的目录
}
DIR* dir=opendir(path);
if(!dir)
{
perror("opendir");
return -1;
}
struct dirent *ent=NULL;
while(ent=readdir(dir))//循环读取子目录文件
{
if(ent->d_name[0]=='.')//不显示隐藏文件
continue;
//printf("%s ",ent->d_name);
if(ent->d_type==DT_DIR)//判断是不是目录
printf("\033[1;34m %s \033[0m",ent->d_name);
// if(ent->d_type==DT_REG)
// printf("\033[1;30m %s \033[0m",ent->d_name);
else
{
char fullpath[NAME_MAX+1]={0};
sprintf(fullpath,"%s%s",path,ent->d_name);//将目录下文件连接到目录路径下
struct stat st={0};
stat(fullpath,&st);
if(st.st_mode&(S_IXUSR|S_IXGRP|S_IXOTH))//如果目录下文件有执行权限
printf("\033[1;32m %s \033[0m",ent->d_name);
else
printf("%s",ent->d_name);
}
}
printf("\n");
closedir(dir);//关闭目录
return 0;
}