ls命令:显示当前目录下有哪些文件
代码实现:
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
#include <dirent.h>
#include <sys/stat.h>
int main()
{
char path[256] = {0};
getcwd(path,256);
DIR *p = opendir(path);
if(p == NULL)
{
perror("opendir error");
exit(0);
}
struct dirent *s = NULL;
while((s = readdir(p)) != NULL)
{
if(strncmp(s->d_name,".",1) == 0)
{
continue;
}
struct stat st;
lstat(s->d_name,&st);
if(S_ISREG(st.st_mode))
{
if(st.st_mode & (S_IXUSR | S_IXGRP | S_IXOTH))
{
printf("\033[1;32m%s \033[0m",s->d_name);
}
else
{
printf("%s ",s->d_name);
}
}
else if(S_ISDIR(st.st_mode))
{
printf("\033[1;34m%s \033[0m",s->d_name);
}
//printf("%s ",s->d_name);
}
printf("\n");
closedir(p);
exit(0);
}
运行结果:
ls命令暂时还没有加参数 有兴趣的可以自己实现一下加参数的ls命令