簡單實現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;
}