搜索引擎技术之文件目录遍历
前面提到了反向索引的设计,简单的说就是对一个目标文件进行解析操作,那么我们要如何先获得这个文件呢?在搜索引擎中,网络蜘蛛程序将所到达的网页一并download到服务器上,成为一个大的文件目录(这里我特别说一下,我的这个说法是不正确的,Google是通过zlib压缩和寻址的方式定位文件,稍后的文章我用实际代码来演示,这里主要是针对简单无压缩的和桌面搜索引擎),里面有很多的文件,我们要做的是遍历整个目录,然后对每个文件中的词条都建立反向索引表.
所以有一个好的遍历算法速度会快很多,很多考试的内容也热衷于遍历和排序,好像这个基本功,我想如果你没有超过微软的工程师的能力,那就安心使用MSDN提供的文件遍历函数吧,FindFile和FindNextFile,这两个好用的函数都由CFileFind类友情提供,特别指出,FindFile的参数是File Filter,在遍历时采用循环的方式对当前目录下所有文件进行遍历,但不是递归的,所以子目录下文件看不到,这里截取部分代码:
//All right revsered by yoki2009
//mailto:imj040144@tom.com
//Welcome to my blog: http://blog.csdn.net/yoki2009
CFileFind finder;
BOOL bWorking = finder.FindFile(m_filter);
while (bWorking)
{
bWorking = finder.FindNextFile();
if (finder.IsDots())
{
continue;
}
else if (finder.IsDirectory())
{
DoSubDirSearch(finder.GetFilePath().GetBuffer());
}else
{
m_ctrlList.InsertItem(_index,finder.GetFileName());
m_ctrlList.SetItemText(_index,0,finder.GetFileName());
m_ctrlList.SetItemText(_index,1,finder.GetRoot());
m_ctrlList.SetItemText(_index,2,finder.GetFilePath());
}
}
大家可能注意到DoSubDirSearch(finder.GetFilePath().GetBuffer());这句话了,这个函数就是我为实现遍历整个子目录而实现的递归调用:
DoSubDirSearch(char * path)
{
chdir(path);
int _index = 0;
CFileFind finder;
BOOL bWorking = finder.FindFile(m_filter);
while (bWorking)
{
bWorking = finder.FindNextFile();
if (finder.IsDots())
{
continue;
}
else if (finder.IsDirectory())
{
DoSubDirSearch(finder.GetFilePath().GetBuffer());
}
}
}