您的位置:首页 > 运维架构 > Linux

linux 目录递归遍历

2009-10-28 08:19 447 查看
第一版程序没有过滤掉目录内的文件。原来readdir()不只是读取目录的,这个和它的函数名不一致。

程序通过

lstat(dirp->d_name, &statbuf);

if(S_ISDIR(statbuf.st_mode))来判断文件是否为目录

#include <iostream>
#include "apue.h"
#include <dirent.h>
using namespace std;
void lsDir(char *d_name)
{
DIR				*dp;
struct dirent	*dirp;
struct stat statbuf;
char localDir[256];

lstat(d_name, &statbuf);
if(!S_ISDIR(statbuf.st_mode))
{
return;
}

if((dp = opendir(d_name)) == NULL)
{
cout << "cant's open " << d_name << endl;
return;
}
cout << d_name << endl;

while((dirp = readdir(dp)) != NULL)
{
if(strcmp(".", dirp->d_name) == 0 ||
strcmp("..", dirp->d_name) == 0)
{
continue;
}

lstat(dirp->d_name, &statbuf);
if(!S_ISDIR(statbuf.st_mode))
{
continue;
}

strcpy(localDir,d_name);
strcat(localDir, "/");
strcat(localDir, dirp->d_name);
lsDir(localDir);
}
closedir(dp);

}
int main(int argc, char* argv[])
{
if(argc !=2 )
{
cout << "usage:ls directory_name" << endl;
return -1;
}

cout <<  "argv:" <<  argv[1] << endl;
lsDir(argv[1]);
exit(0);

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: