【windows c】 遍历目录

方式一:

DWORD z_dRed = 0;
char z_FilePath[MAX_PATH] = {0};
char z_newPath[MAX_PATH] = {0};
char z_tmpPath[MAX_PATH] = {0};
char *z_dir = NULL;
WIN32_FIND_DATA wfd;
ZeroMemory(&wfd, sizeof(wfd));

sprintf_s(z_FilePath,512, "%s\*.*",folderPath);
HANDLE hFind = FindFirstFile(z_FilePath, &wfd);
if (hFind == INVALID_HANDLE_VALUE)
{
return FALSE;
}

do
{
char* strFileName = wfd.cFileName;

if (0 == strcmp(strFileName, ".") || 0 == strcmp(strFileName, "..") )
{
continue;
}

#ifdef _WIN32
sprintf(z_newPath, "%s%s%s", folderPath, "\", strFileName);
#else
sprintf(z_newPath, "%s%s%s", folderPath, "/", strFileName);
#endif

if ((wfd.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) != 0)
{
z_dRed = AddDirToZip(zf, z_newPath);
}
else
{
char z_savepath[MAX_PATH] = {0};
sprintf(z_tmpPath, "%s", z_newPath);
PathRemoveFileSpec(z_tmpPath);

if (g_dirCount > strlen(z_tmpPath))
{
printf("error zip file: %s ", z_newPath);
continue;
}

z_dir = &(z_tmpPath[g_dirCount]);

z_dRed = AddFileToZip1(zf, z_newPath, z_dir);
}

} while (FindNextFile(hFind, &wfd));

return z_dRed;

方式二:

DWORD CFolderDelete::TransferFolder_T( IN WCHAR * folderPath, IN FILEOPERFUNC func , IN WCHAR * fileNameFltDoNothing, IN WCHAR separator )
{
LOG(L"7777777777777777777777 TransFolder In %s 7777777777777777777777。 ", folderPath);
USES_CONVERSION;
int z_Ret = ERROR_TASKOP_OK;
CFileFind z_FileFind;
WCHAR z_FilePath[512] = {0};
WCHAR z_TarPath[MAX_PATH]={0};
bool z_SomeFileDeleteFailed = false;

if (_tcslen(folderPath)<4)
{
return ERROR_TASKOP_OTHER;
}

DWORD z_Flag = GetFileAttributes(folderPath);

if (z_Flag==(UINT)-1||!(z_Flag&FILE_ATTRIBUTE_DIRECTORY))
{
return ERROR_TASKOP_OTHER;
}

swprintf_s(z_FilePath,512, L"%s\*.*",folderPath);

BOOL z_IsFinded = z_FileFind.FindFile(z_FilePath);
while (z_IsFinded)
{
z_IsFinded = z_FileFind.FindNextFile();

if (!z_FileFind.IsDots())
{
WCHAR z_TempDir[512]={0};
swprintf_s(z_TempDir,512, L"%s\%s", folderPath, z_FileFind.GetFileName());

if (fileNameFltDoNothing != NULL && separator != NULL)
{
if (IsElemInSet(z_FileFind.GetFileName().GetBuffer(), fileNameFltDoNothing, separator))
{
LOG(L"7777777777777777777777 %s 不再遍历7777777777777777777777。 ", z_TempDir);
continue;
}
}

if (z_FileFind.IsDirectory())
{
z_Ret = TransferFolder_T(z_TempDir, func, fileNameFltDoNothing, separator);
}
else
{
if (func!=NULL)
{
LOG(L"7777777777777777777777 %s 删除 !!7777777777777777777777。 ", z_TempDir);
func(z_TempDir);
}
}
}

}

z_FileFind.Close();

if(!RemoveDirectory(folderPath))
{
LOG(L"##########XXY########## 删除目录 %s 失败。##########XXY########## ", folderPath);
z_Ret = ERROR_TASKOP_OTHER;
}

LOG(L"7777777777777777777777 TransFolder Out %s 7777777777777777777777。 ", folderPath);

return z_Ret;
}

原文地址:https://www.cnblogs.com/whwywzhj/p/8409415.html