Unix/Linux如何遍历一个目录下所有的文件

Posted on 2012-07-29 10:05 卡洛shll 阅读(2765) 评论(2)  编辑 收藏 引用 所属分类: C/C++
      网络上流传一种方案,用opendir(), readdir(),closedir()方式解决。我也尝试使用,发现不能解决我的需求。这种方案,仅仅能遍历给出所有的文件名,估计效率比较高吧。一旦遍历中需要对文件进行操作就会发生意想不到的事情,比如进入了死循环,程序一直在while readdir()中纠结。下面贴上网络上流传的这段代码:

#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <dirent.h>
int testdir(char *path)
{
 struct stat buf;
 if(lstat(path,&buf)<0)
 {
  return 0;
 }
 if(S_ISDIR(buf.st_mode))
 {
  return 1; //directory
 }
 return 0;
}


int directory(char *path)
{
 DIR *db;
 char filename[128];
 struct dirent *p;
 db=opendir(path);
 if(db==NULL)return 0;
 memset(filename,0,128);
 while ((p=readdir(db)))
 {
  if((strcmp(p->d_name,".")==0)||(strcmp(p->d_name,"..")==0))
   continue;
  else
  {
   sprintf(filename,"%s/%s",path,p->d_name);
   if(testdir(filename))
   {
    directory(filename);
   }
   else {
    printf("%s/n",filename);
   }
  }
  memset(filename,0,64);
 }
 closedir(db);
 return 0;
}
int main(int argc,char **argv)
{
 char *path="./"; //要遍历的目录
 if(access(path,F_OK)==0&&testdir(path))
 {
  printf("is directory/n");
  directory(path);
 }
 else printf("%s not exist/n",path);
}


      后来我又找到了另外还有一种方案,这种方案能帮我解决不能打开文件进行操作的疑惑。主要是使用ftw.h里的方法,该头文件意义是 file tree wall文件目录树遍历:先贴上代码:


#include <iostream>
#include <fstream>
using namespace std;

#include <string.h>
#include <ftw.h>

int fn(const char* file, const struct stat* sb, int flag)
{
    char    line[256] = {0};
    int     count = 0;

    if (flag == FTW_F) {    // 如果是文件
        cout<<"The File's name : "<<file<<endl;
        /*
        ifstream file(file);
        if (file.isopen()) {
            file.getline(line, 100);
            cout<<line<<endl;
        }
        */
       
        FILE*   fp;
        fp = fopen(file, "r");
        fgets(line, sizeof(line), fp);
        fclose(fp);
        printf("Line's data######## : %s\n", line);
       
    }else if (flag == FTW_D) {  // 如果是子目录(遍历的第一个是根目录)
        cout<<"The Directory name : "<<file<<endl;
    }

    return 0;
}

int main(int argc, char** argv)
{
    ftw("home/~", fn, 0);
    return 0;
}




Feedback

# re: Unix/Linux如何遍历一个目录下所有的文件  回复  更多评论   

2012-10-25 10:56 by 小凤儿_vir
我按照你的方式用了这个FTW函数,但是在linux下,跑步起来,为什么啦?

# re: Unix/Linux如何遍历一个目录下所有的文件  回复  更多评论   

2012-10-26 13:05 by 卡洛shll
请帖上你的源代码@小凤儿_vir

只有注册用户登录后才能发表评论。
网站导航: 博客园   IT新闻   BlogJava   知识库   博问   管理