怎样在目录中寻找文件

下面的代码说明了怎样在一个给定的目录中从上到下地搜索整个目录树.本例子只将结果输出到system debug screen.

调用下面的类函数,搜索完成之后,将出现一个信息框.

void CTestView::OnSearch() 
{

// szFilename is declared in the header as array of char
// look for MyFile.txt (or whatever)

strcpy(szFilename,"MyFile.txt");

// go to root directory (or to whichever directory that you wish)

_chdir("C://");

// search for the filename

SearchDirectory();

// announce when done

MessageBox("Done Searching"); 
}

函数 SearchDirectory() 在函数 OnSearch()中被调用. SearchDirectory() 然后反复回调,直到整个目录,包括子目录都被搜索.

void CTestView::SearchDirectory() 
{
struct _finddata_t filestruct;
long hnd;
char buffer[_MAX_PATH];

// set _findfirst to find everthing

hnd = _findfirst("*",&filestruct);

// if handle fails, drive is empty...

if((hnd == -1)) return;

// get first entity on drive - check if it's a directory

if(::GetFileAttributes(filestruct.name) & FILE_ATTRIBUTE_DIRECTORY 
&& !(::GetFileAttributes(filestruct.name) & FILE_ATTRIBUTE_HIDDEN)) { 

// if so, change to that directory and recursively call SearchDirectory

if(*filestruct.name != '.') { 

_chdir(filestruct.name);

SearchDirectory();

// go back up one directory level

_chdir("..");
}

else {

// if it's not a directory and it matches what you want...

if(!stricmp(filestruct.name,szFilename)) {

// output the filename with path to debugger

_getcwd(buffer,_MAX_PATH);
strcat(buffer,"//");
strcat(buffer,filestruct.name); 
strcat(buffer,"/r/n");
OutputDebugString(buffer);

}

while(!(_findnext(hnd,&filestruct))) {

if(::GetFileAttributes(filestruct.name) & FILE_ATTRIBUTE_DIRECTORY 
&& !(::GetFileAttributes(filestruct.name) & FILE_ATTRIBUTE_HIDDEN)) {

if(*filestruct.name != '.') { 
_chdir(filestruct.name);

SearchDirectory();

_chdir("..");
}
}
else {

if(!stricmp(filestruct.name,szFilename)) {
_getcwd(buffer,_MAX_PATH); 
strcat(buffer,"//");
strcat(buffer,filestruct.name);
strcat(buffer,"/r/n");
OutputDebugString(buffer);
}
}
}

_findclose(hnd); 
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值