linux -my ls

这里写代码片
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <assert.h>
#include <string.h>
#include <sys/types.h>
#include <dirent.h>
#include <sys/stat.h>

void main()
{
    char path[128] = {0};
    getcwd(path,127);//获取当前路径
    if(strlen(path) == 0)//路径位空时返回
    {
        return;
    }

    DIR *dir = opendir(path);//打开路径,将路径中的文件
    struct dirent *p = NULL;//用dirent函数扫描指针所指向的文件目录
    while((p = readdir(dir)) != NULL)//打开文件成功时
    {
        if(strncmp(p->d_name,".",1) == 0)//过滤掉隐藏属性的文件
        {
            continue;
        }
        struct stat buf;//用struct stat类型的结构体存放文件的相关属性
        lstat(p->d_name,&buf);//将文件名存放在buf
        if(S_ISDIR(buf.st_mode))
        {
            printf("\033[1;34m%s     \033[0m",p->d_name);
            continue;
        }
        else if(S_ISFIFO(buf.st_mode))//目录文件 蓝色
        {
            printf("\033[40;33m%s\033[0m",p->d_name);
            printf("     ");
            continue;
        }
        else if(buf.st_mode & S_IXUSR ||
                buf.st_mode & S_IXGRP ||
                buf.st_mode & S_IXOTH)//可执行文件 绿色
        {
            printf("\033[1;32m%s     \033[0m",p->d_name);
            continue;
        }
        printf("%s     ",p->d_name);//普通文件直接打印
    }
    printf("\n");
    closedir(dir);
}

“`

猜你喜欢

转载自blog.csdn.net/s_yj_q/article/details/78078449
今日推荐