遍历目录树

来源:互联网 发布:怎么看linux系统版本 编辑:程序博客网 时间:2024/05/17 10:41

     1  #include <iostream>
     2  using namespace std;
     3  #include <unistd.h>
     4  #include <sys/stat.h>
     5  #include <dirent.h>
     6  #include <string>
     7  #include <list>
     8  #include <iomanip>
     9
    10  int dir(const char* name, int level=0)
    11  {
    12      if(level>0)
    13          cout << setw(level*2) << ' ';
    14      cout << name;
    15      if(chdir(name)<0){
    16          cout << endl;
    17          return 0;
    18      }
    19      list<string> ls;
    20      DIR* p=opendir(".");
    21      dirent* q;
    22      while((q=readdir(p))!=NULL)
    23          if(q->d_name[0]!='.')
    24              ls.push_back(q->d_name);
    25      closedir(p);
    26      ls.sort();
    27      int cnt=ls.size();
    28      cout << "==>" << cnt << " items:" << endl;
    29      list<string>::iterator it;
    30      for(it=ls.begin(); it!=ls.end(); ++it){
    31          cnt+=dir(it->c_str(), level+1);
    32      }
    33      chdir("..");
    34      return cnt;
    35  }
    36  int main(int argc, char* argv[])
    37  {
    38      char* p=".";
    39      if(argc==2)
    40          p = argv[1];
    41      dir(p);
    42  }
    43

原创粉丝点击