腾讯面试:Linux下如何扫描目录

问题:在linux下,输出某个文件夹下的文件即其子目录,以及子目录下的文件和文件夹。

代码如下:

#include<iostream>
#include<unistd.h>
#include<sys/stat.h>
#include<sys/types.h>
#include<dirent.h>
#include<fcntl.h>
#include<string.h>

/*值得注意的是: struct stat statBuf;
  1.如果声明为 struct stat * statBuf,后面用指针方式操作的时候,总是出错。
  2.必须使用chdir,否则不在文件所在目录工作的话,S_ISDIR会将文件判定为文件夹而引发错误。
 */

using namespace std;

int  printDir(const char * dirPath)
{
     DIR * dir;
     struct dirent * entry;
     struct stat  statBuf;
        
    if ((dir=opendir(dirPath))==NULL)
       {
          cout<<"error when open the directory!"<<endl;
          return -1;
        }
    else
       {  
          chdir(dirPath);
          while((entry=readdir(dir))!=NULL)
          { 
              lstat(entry->d_name,&statBuf);
              if (S_ISDIR(statBuf.st_mode))
              {
                 if ((strcmp(".",entry->d_name)==0)||(strcmp("..",entry->d_name)==0)) continue;
                 cout<<"this is a directory"<<entry->d_name<<endl;
                 printDir(entry->d_name);                 
              }
              else   cout<<"this is a document"<<entry->d_name<<endl;              
           }
           chdir("..");
           closedir(dir);
        }
}


int main()
{
    printDir(".");
    return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值