BCB新建线程DeleteImgThread
类,其会默认继承Thread类,然后在Execute函数中编写代码,
void __fastcall DeleteImgThread::Execute()
{
//---- Place thread code here ----
while(!this->Terminated)
{
//删除.\RecvTmp中的图片
AnsiString JepgDir = ExtractFilePath(ParamStr(0)) + "RecvTmp";
TSearchRec sr;
int iAttributes = faAnyFile;
if (FindFirst(JepgDir+ "\\*.jpg", iAttributes, sr) == 0)
{
do
{
TDateTime JepgTime = FileDateToDateTime(sr.Time);
if (Now()-1 > JepgTime)
{
DeleteFile(JepgDir + "\\"+ sr.Name);
}
}
while(FindNext(sr) == 0);
}
FindClose(sr);
Sleep(5000);
}
}
这里声明了一个系统结构体SearchRec变量sr,用于遍历文件夹,文件,与FindFirst、FindNext配合使用,使用系统基本函数DeleteFile()删除文件,注意sr使用完之后一定要FindClose(sr),不然会导致句柄不断增加。一般使用系统变量的话都需要手动将其注销掉,不然会引起句柄不断增加。
创建好线程类之后,需要在主函数中声明调用
DeleteImgThread *DeleteImg;
DeleteImg = new DeleteImgThread(NULL); // 清除以前接收的图片
new一个对象出来就一定要delete掉,切记!
//释放DeleteImgThread线程
if (DeleteImg)
{
DeleteImg->Terminate();
DeleteImg->Resume();
DeleteImg->WaitFor();
delete DeleteImg;
DeleteImg=NULL;
}