C++里如何从一个目录里递归查找指定的文件

2025-10-24 17:54:11

1、先完成找文件的函数:

void GetFileInDir(string dirName)

{

DIR *Dir=NULL;

struct dirent *file=NULL;

if(dirName[dirName.size()-1]!='/')

{

dirName+="/";

}

if((Dir=opendir(dirName.c_str()))==NULL)

{

cerr<<"Can't open Directory"<<endl;

exit(1);

}

while(file=readdir(Dir))

{

//if the file is a normal file

if(file->d_type==DT_REG)

{cout<<dirName+file->d_name<<endl;

}

//if the file is a directory

else if(file->d_type==DT_DIR&&strcmp(file->d_name,".")!=0&&strcmp(file->d_name,"..")!=0)

{

GetFileInDir(dirName+file->d_name);

}

}

}

2、加入main函数

相应的main 函数:

int main(int argc,char*argv[])

{

if(argc<2)

{

cerr<<"NeedDirectory"<<endl;

exit(1);

}

string dir=argv[1];

GetFileInDir(dir);

}

3、随后加入要找的文件,从main 函数中穿参数到函数GetFileInDir

GetFileInDir(dir, filename)

然后再GetFileInDir 函数中多加一个文件是否找到的判断

GetFileInDir

声明:本网站引用、摘录或转载内容仅供网站访问者交流或参考,不代表本站立场,如存在版权或非法内容,请联系站长删除,联系邮箱:site.kefu@qq.com。
猜你喜欢