程序如下:
#include <windows.h>
#include <tchar.h>
#include <stdio.h>
#include<conio.h>
#include<time.h>
#include<stdlib.h>
int find=0;
void FindAndExecuteFile(const TCHAR* rootDirectory, const TCHAR* fileName) {
TCHAR searchPath[MAX_PATH];
_stprintf(searchPath, _T("%s\\*"), rootDirectory);WIN32_FIND_DATA findFileData;
HANDLE hFind = FindFirstFile(searchPath, &findFileData);if (find==0&&hFind == INVALID_HANDLE_VALUE) {
_tprintf(_T("Error searching for files in directory: %s\n"), rootDirectory);
return;
}do {
if (find==0&&_tcscmp(findFileData.cFileName, _T(".")) != 0 && _tcscmp(findFileData.cFileName, _T("..")) != 0) {
if (find==0&&findFileData.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) {
TCHAR subDirectory[MAX_PATH];
_stprintf(subDirectory, _T("%s\\%s"), rootDirectory, findFileData.cFileName);
FindAndExecuteFile(subDirectory, fileName);
} else {
if (find==0&&_tcscmp(findFileData.cFileName, fileName) == 0) {
system("cls");
_tprintf(_T("File found: %s\\%s\n"), rootDirectory, findFileData.cFileName);
find=1;
}
}
}
} while ((find==0)&&FindNextFile(hFind, &findFileData) != 0);//FindClose(hFind);
}void FindAndExecuteFileInAllDrives(const TCHAR* fileName) {
for (TCHAR drive = _T('Z'); drive >= _T('A'); --drive) {
TCHAR rootDirectory[MAX_PATH];
_stprintf(rootDirectory, _T("%c:\\"), drive);FindAndExecuteFile(rootDirectory, fileName);
}
}int main() {
char fileName[MAX_PATH];
R: find=0;
system("cls");
printf(_T("Enter the file name to search: "));
gets(fileName);
FindAndExecuteFileInAllDrives(fileName);
if(find==1)printf("\n%s has been found!\n",fileName);
else {
system("cls");printf("\nDon't find %s!\n",fileName);
}
getch();
goto R;
}
注意,在查找文件时必须加上文件后缀。