Yêu cầu của bạn là duyệt tìm trong ổ đĩa mọi file index.dat rồi xóa hết đi. Đây là 1 chức năng rất thiết yếu trong hoạt động quản lý hệ thống file, nó dựa vào giải thuật duyệt file đệ qui. Windows cung cấp 2 hàm API tên là FindFirstFile() và FindNextFile() để giúp người lập trình viết giải thuật duyệt đệ qui hệ thống file. Sau đây là mã nguồn hàm duyệt và xóa file viết bằng VC++:
Code:
//----------------------------------
// Duyệt đệ qui và xóa file theo pattern qui định
// thí dụ nếu pattern=”c:\index.dat” thì hàm sẽ tìm và xóa
// hết các file index.dat trên đĩa c:
//----------------------------------
void CXoaDequiDlg::DuyetVaXoa (char *pattern) {
char drive[4], directory[1024], patname[9], patext[5];
char buff[1024], filename[9], file_ext[5];
WIN32_FIND_DATA pblock;
HANDLE hSearch;
WORD dwRC;
// tách pattern ra các thành phần cơ bản
_splitpath(pattern, drive, directory, patname, patext);
// xây dựng lại pattern cần duyệt
sprintf(buff,”%s%s*.*”,drive,directory);
// tìm phần tử đầu thỏa pattern
hSearch=FindFirstFile(buff,&pblock);
if (hSearch!=(HANDLE) -1) dwRC=1; else dwRC=0;
while (dwRC) { // trong khi còn phần tử thỏa pattern
//không xử lý label, thư mục hiện hành và thư mục cha
if (strcmp(pblock.cFileName,”.”)==0 || strcmp(pblock.cFileName,”..”) ==0 || (pblock.dwFileAttributes & FILE_ATTRIBUTE_SYSTEM)){
dwRC=FindNextFile(hSearch,&pblock); continue;
}
// tách tên file ra 2 thành phần cơ bản
_splitpath(pblock.cFileName, buff, buff, filename, file_ext);
if (pblock.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) {
// nếu thành phần tìm được là thư mục
// chỉ duyệt và xóa các thành phần con của nó thỏa pattern
sprintf(buff,”%s%s%s\\%s%s”,drive,directory, pblock.cFileName, patname, patext);
DuyetVaXoa(buff);
} else { // nếu là file
char patternName[256];
sprintf(patternName,”%s%s”,patname, patext);
if (strcmp(patternName,pblock.cFileName)==0) {
// đúng file cần xóa ==> xóa nó
// xây dựng pathname tuyệt đối của file cần xóa
sprintf(buff,”%s%s%s”,drive,directory,pblock.cFileName);
if (pblock.dwFileAttributes & FILE_ATTRIBUTE_READONLY)
// xóa thuộc tính readonly
SetFileAttributes(buff,pblock.dwFileAttributes & (~FILE_ATTRIBUTE_READONLY));
// xóa file
DeleteFile(buff);
}
}
// tìm phần tử kế tiếp
dwRC=FindNextFile(hSearch,&pblock);
}
}
Theo goctinhoc