下面的代码说明了怎样在一个给定的目录中从上到下地搜索整个目录树.本例子只将结果输出到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);
}
-
近期文章
近期评论
- coolker 发表在《打造最快的Hash表》
- struggle 发表在《提供C语言教学课件(适用于初学者)》
- zhanghaibo 发表在《提供C语言教学课件(适用于初学者)》
- zhanghaibo 发表在《提供C语言教学课件(适用于初学者)》
- diys 发表在《C语言编程宝典(王大刚) 1.1 C 语言的产生与发展》
文章归档
- 2022 年十月
- 2014 年一月
- 2013 年十二月
- 2012 年十一月
- 2012 年七月
- 2012 年六月
- 2012 年五月
- 2012 年四月
- 2012 年三月
- 2012 年二月
- 2011 年十二月
- 2011 年十月
- 2011 年九月
- 2011 年八月
- 2011 年七月
- 2011 年六月
- 2011 年五月
- 2011 年四月
- 2011 年三月
- 2011 年二月
- 2011 年一月
- 2010 年十二月
- 2010 年十一月
- 2010 年十月
- 2010 年九月
- 2010 年八月
- 2010 年七月
- 2010 年六月
- 2010 年五月
- 2010 年四月
- 2010 年三月
- 2010 年二月
- 2010 年一月
- 2009 年十二月
- 2009 年十一月
- 2009 年十月
- 2009 年九月
- 2009 年八月
- 2009 年七月
- 2009 年六月
- 2009 年五月
- 2009 年四月
- 2009 年三月
- 2009 年二月
- 2009 年一月
- 2008 年十二月
- 2008 年十一月
- 2008 年十月
- 2008 年九月
- 2008 年八月
- 2008 年七月
- 2008 年六月
- 2008 年五月
- 2008 年四月
- 2008 年三月
- 2008 年二月
- 2008 年一月
- 2007 年十二月
- 2007 年十一月
- 2007 年十月
- 2007 年九月
- 2007 年八月
- 2007 年七月
- 2007 年六月
- 2007 年三月
- 2007 年二月
- 2007 年一月
- 2006 年十二月
- 2006 年十一月
- 2006 年十月
- 2006 年九月
- 2006 年八月
- 2006 年七月
- 2006 年六月
- 2006 年五月
- 2006 年四月
- 2006 年三月
- 2006 年二月
- 2006 年一月
- 2005 年十二月
- 2005 年十一月
分类目录
功能