FindFirstFile和FindNextFile
#include <windows.h>
#include <stdio.h>
#define MAC_FILENAMELENOPATH 256
void FindFileInDir(char* rootDir, char* strRet)//第一个参数是输入的目录名,第二个参数是存放所有文件的缓冲
{
char fname[MAC_FILENAMELENOPATH];
ZeroMemory(fname, MAC_FILENAMELENOPATH);
WIN32_FIND_DATA fd;
ZeroMemory(&fd, sizeof(WIN32_FIND_DATA));
HANDLE hSearch;
char filePathName[256];
char tmpPath[256];
ZeroMemory(filePathName, 256);
ZeroMemory(tmpPath, 256);
strcpy(filePathName, rootDir);
BOOL bSearchFinished = FALSE;
if( filePathName[strlen(filePathName) -1] != '\\' )
{
strcat(filePathName, "\\");//自动在输入的文件目录下面加上“\”
}
strcat(filePathName, "*");//当前目录的全部子目录和文件
hSearch = FindFirstFile(filePathName, &fd);
//Is directory
if( (fd.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY)
&& strcmp(fd.cFileName, ".") && strcmp(fd.cFileName, "..") ) //.表示当前目录,..表示上一级目录
{
strcpy(tmpPath, rootDir);
strcat(tmpPath, fd.cFileName);
FindFileInDir(tmpPath, strRet);
}
else if( strcmp(fd.cFileName, ".") && strcmp(fd.cFileName, "..") )
{
sprintf(fname, "%s\n", fd.cFileName);
strcat(strRet + strlen(strRet) , fname);//这个地方和网上的有差别
}
while( !bSearchFinished )
{
if( FindNextFile(hSearch, &fd) )
{
if( (fd.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY)
&& strcmp(fd.cFileName, ".") && strcmp(fd.cFileName, "..") )
{
strcpy(tmpPath, rootDir);
strcat(tmpPath, "\\");//这个地方网上的程序都没有写,会造成错误
strcat(tmpPath, fd.cFileName);
FindFileInDir(tmpPath, strRet);
}
else if( strcmp(fd.cFileName, ".") && strcmp(fd.cFileName, "..") )
{
sprintf(fname, "%s\n", fd.cFileName);
strcat(strRet + strlen(strRet), fname);//这个地方和网上的也有差别
}
}
else
{
if( GetLastError() == ERROR_NO_MORE_FILES ) //Normal Finished
{
bSearchFinished = TRUE;
}
else
bSearchFinished = TRUE; //Terminate Search
}
}
FindClose(hSearch);
}
void main()//用于测试的主程序
{
char rootDir[100]={0};
char strRet[99999]={0};
strcpy(rootDir,"C:\\wince300");
FindFileInDir( rootDir, strRet);
printf("%s",strRet);
}