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

网络上流传一种方案,用opendir(), readdir(),closedir()方式解决。我也尝试使用,发现不能解决我的需求。这种方案,仅仅能遍历给出所有的文件名,估计效率比较高吧。一旦遍历中需要对文件进行操作就会发生意想不到的事情,比如进入了死循环,程序一直在while readdir()中纠结。下面贴上网络上流传的这段代码:

#include

#include

#include

#include

#include

#include

#include

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

#include

using namespace std;

#include

#include

int fn(const char* file, const struct stat* sb, int flag)

{

char    line[256] = {0};

int     count = 0;

if (flag == FTW_F) {    // 如果是文件

cout<

/*

ifstream file(file);

if (file.isopen()) {

file.getline(line, 100);

cout<

}

*/

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<

}

return 0;

}

int main(int argc, char** argv)

{

ftw("home/~", fn, 0);

return 0;

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值