FindFile 类,用于 Windows 项目






4.80/5 (24投票s)
2002 年 11 月 28 日
2分钟阅读

180875

2407
这个类旨在减轻在目录中查找文件和文件夹的任务,提供搜索过滤器等选项,例如排除文件过滤器,排除目录过滤器
引言
作为程序员,我们在许多项目中都必须搜索文件和目录。我一直认为肯定有人写过一些东西来让我在这方面更容易。我做了很多搜索,但我发现的大部分都依赖于特定的 IDE,例如 VS 和 MFC。所以,我决定自己写一个,让它独立于 IDE,并添加一些有用的功能。FindFile
是我的努力的结果。
Using the Code
允许搜索的代码由文件 FindFile.h、FindFile.cpp、wildcard.h 和 wildcard.cpp 组成。要使用代码,您需要初始化一个 FindFileOptions_t
结构并将它通过引用传递给 FindFile
的构造函数。以下是该结构的一个片段,列出了 FindFile
使用的选项
struct FindFileOptions_t
{
bool recursive; // Whether to look inside subdirectories
bool returnFolders; // Return folder names as results too
bool *terminateValue; // Value to check to see whether search
// should be terminated
string location; // Where to search for files
string filter; // Filter for files to be included
string excludeFile; // Exclude filter for files
string excludeDir; // Exclude filter for directories
};
其中一些选项需要解释。 returnFolders
选项指定 FindFile
是否应该在其返回结果中同时返回文件和目录。 terminateValue
选项是指向内存中某个整数的指针,将读取其值以确定是否应该中止搜索。这在将此类合并到多线程环境中时非常有用(这种情况最有可能发生)。如果 terminateValue
指向的整数中的值不是 0,则搜索将中止。如果您不想使用此功能,只需将 terminateValue
设置为 NULL
。
以下是使用 FindFile
的程序的示例
FindFileOptions_t opts;
opts.excludeDir = "CSE*;*53*";
opts.excludeFile = "*.pdf;*.doc";
opts.filter = "*";
opts.location = "C:\\School";
opts.recursive = true;
opts.returnFolders = false;
opts.terminateValue = NULL;
FindFile find(opts);
find.search();
int nfiles = (int) find.filelist.size();
__int64 size = find.listsize;
// Print out the list of files found
for (int i = 0; i < (int) find.filelist.size(); i++)
{
string fullname = FindFile::combinePath(find.filelist[i].path,
find.filelist[i].fileinfo.cFileName);
printf("%s\n", fullname.c_str());
}
printf("Found: %d files (%ld bytes)", nfiles, size);
此示例将递归搜索目录 "C:\School" 中的所有文件,这些文件没有 PDF 或 DOC 扩展名,并且不会在以 "CSE" 开头或包含 "53" 的子目录中查找文件。
历史
- 2003 年 12 月 27 日
- 更新源代码以反映修复根驱动器中文件搜索的错误
- 2002 年 11 月 29 日
- 所有对 GNU 公共许可证的引用都已从代码中删除。只要原始版权声明保留在您修改/重新分发的所有版本中,您就可以自由地以任何您认为合适的方式使用此代码。
- 2002 年 11 月 28 日
- 这是该代码的第一个版本,但已在我的许多项目中使用了多年。但是,如果您发现错误,或者觉得某些部分可以做得更好,请告诉我。
许可证
本文没有明确的许可证附加到它,但可能包含在文章文本或下载文件本身中的使用条款。如有疑问,请通过下面的讨论区联系作者。
可以在 这里找到作者可能使用的许可证列表。