delphi多线程文件搜索


本文整理自网络,侵删。

 delphi多线程文件搜索

文件搜索功能要用到findfirst和findnext函数,以及tsearchrec结果,采用深度优先算法,先搜索目录下的文件,然后搜索目录下的子目录递归调用,代码如下

procedure TSearchThread.findfiles(apath: string);
{通过递归调用,可以在当前目录和子目录下查找指定格式的文件}
var
fsearchrec,dsearchrec : tsearchrec;
findresult : integer;
begin
apath:=getdirectoryname(apath); //获取一个有效的目录名称

{查找一个匹配的文件}
findresult:=findfirst(apath+ffilename,faanyfile+fahidden+fasysfile+fareadonly,fsearchrec);
try
{继续查找匹配的文件}
while findresult=0 do
begin
Form1.ListBox1.Items.Add(apath + fsearchrec.Name);
//FileCopy(apath+fsearchrec.Name, LocalPath + fsearchrec.Name);
findresult:=findnext(fsearchrec);
end;

{在当前目录的子目录中进行查找}
//先在当前目录下搜索目录
findresult:=findfirst(apath+'*.*',fadirectory,dsearchrec);
while findresult=0 do
begin
if ((dsearchrec.Attr and fadirectory)=fadirectory) and not
isdirnotation(dsearchrec.Name) then
findfiles(apath+dsearchrec.Name);//在此处是递归调用
findresult:=findnext(dsearchrec);
end;
finally
findclose(fsearchrec);
end;
end;

另外实现的是硬盘搜索,使用了DriveComboBox控件,然后判断驱动器类型,对于软盘和光盘不做搜索对象。代码如下

for i:=0 to Form1.Drive.Items.Count-1 do
begin
C := Copy(Form1.Drive.Items[i], 0, 2);
C := C + '\';
DType := GetDriveType(PChar(C));
if (DType = DRIVE_FIXED) then
findfiles(C);
end;

最后需要说明的是多线程的实现。如果在mainform下找到一个硬盘驱动器就启动一个线程,会产生多个线程,不好控制,比如按下停止按钮终止这些线程等,所以就考虑把上面的循环判断放到从线程中处理。这样当它执行findfiles的时候就可以阻塞等待。

待解决的问题,1。如何搜索多种文件 2。如果把循环判断驱动器类型放到mainform中,启动搜索线程后又该如何阻塞(winexec我认为就是启动从线程序,但有办法阻塞到其终止)

相关阅读 >>

Delphi tstringlist自定义排序

Delphi shgetfileinfo函数获取任何文件大图标

Delphi 检查屏幕是否处于锁屏或关闭状态

Delphi unigui unistringgrid1 清空

Delphi 按字符串长度对tstringlist的元素进行排序

Delphi xe 7 mediaplayer 在安卓里放不出声音

Delphi 条件编译语法 $ifdef $else $endif

Delphi 字符串连接

Delphi 合并文本行的函数

Delphi 实现窗口记住关闭时的坐标位置

更多相关阅读请进入《Delphi》频道 >>



打赏

取消

感谢您的支持,我会继续努力的!

扫码支持
扫码打赏,您说多少就多少

打开支付宝扫一扫,即可进行扫码打赏哦

分享从这里开始,精彩与您同在

评论

管理员已关闭评论功能...