lilnux C++遍历目录

35 篇文章 0 订阅
#include<unistd.h> 
#include<stdio.h>
 #include<string.h>
#include<sys/stat.h>
#include<dirent.h>

//获得目录的函数,第一个参数是根目录 ,第二个参数是挖掘深度
void printdir(char*dir,int mark)
{
    DIR *dp=NULL;
    struct dirent *entry=NULL;
    struct stat statbuf={0};
    if((dp=opendir(dir))==NULL)
    {
       printf("i am sorry can not open the dir%s",dir);
       return;
    }
    chdir(dir);//chdir函数是做什么的?,改变当前目录成为指定目录
    while((entry=readdir(dp))!=NULL)
    {
       lstat(entry->d_name,&statbuf);
       if(S_ISDIR(statbuf.st_mode))
       {
          //如果是目录文件的话i,看看是不是自己或者父目录
          if(strcmp(".",entry->d_name)==0)
          {
                continue;
          } 
          if(strcmp("..",entry->d_name)==0)
          {
                continue; 
           }
          //如果不是打印出当前文件名称
          printf("文件夹:%s\n",entry->d_name); 
           if(mark==1)
           printdir(entry->d_name,3); 
       }
       else
       {
            printf("文件名称:%s\n",entry->d_name);
       } 
    }
    chdir("..");
    closedir(dp);
}
int main(int argc,char* argv[])
{
     char* topdir,pwd[2]=".";
     if(argc!=3)
     {
         printf("Invalid Arguments\n");
         return;
     }
     else
      topdir=argv[1];
     if(strcmp(argv[2],"s")==0)

        printdir(topdir,1);
      else
        printdir(topdir,0);
}

本来是想printdir的第二个参数是bool类型的,可是gcc编译器没有定义,也就只能退而求其次,使用int类型的了,如果有参数s则遍历时使用递归遍历
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

世纪殇

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值