实现ls功能

简单实现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;
}
  • 3
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值