如何递归遍历目录使用C在Windows [英] How to recursively traverse directories in C on Windows
问题描述
最后,我想通过一个文件夹的文件和子目录旅行和写的东西我发现所有的文件有一定的扩展名(.WAV在我的情况)。循环时我怎么知道是否我的产品目录?
Ultimately I want to travel through a folder's files and subdirectories and write something to all files i find that have a certain extension(.wav in my case). when looping how do i tell if the item I am at is a directory?
推荐答案
下面是你如何做到这一点(这是所有从内存中,因此有可能是错误的):
Here is how you do it (this is all from memory so there may be errors):
void FindFilesRecursively(LPCTSTR lpFolder, LPCTSTR lpFilePattern)
{
TCHAR szFullPattern[MAX_PATH];
WIN32_FIND_DATA FindFileData;
HANDLE hFindFile;
// first we are going to process any subdirectories
PathCombine(szFullPattern, lpFolder, _T("*"));
hFindFile = FindFirstFile(szFullPattern, &FindFileData);
if(hFindFile != INVALID_HANDLE_VALUE)
{
do
{
if(FindFileData.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY)
{
// found a subdirectory; recurse into it
PathCombine(szFullPattern, lpFolder, FindFileData.cFileName);
FindFilesRecursively(szFullPattern, lpFilePattern);
}
} while(FindNextFile(hFindFile, &FindFileData));
FindClose(hFindFile);
}
// Now we are going to look for the matching files
PathCombine(szFullPattern, lpFolder, lpFilePattern);
hFindFile = FindFirstFile(szFullPattern, &FindFileData);
if(hFindFile != INVALID_HANDLE_VALUE)
{
do
{
if(!(FindFileData.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY))
{
// found a file; do something with it
PathCombine(szFullPattern, lpFolder, FindFileData.cFileName);
_tprintf_s(_T("%s\n"), szFullPattern);
}
} while(FindNextFile(hFindFile, &FindFileData));
FindClose(hFindFile);
}
}
所以,你可以调用这个像
So you could call this like
FindFilesRecursively(_T("C:\\WINDOWS"), _T("*.wav"));
要找到所有在C * .wav文件:\\ WINDOWS及其子目录
to find all the *.wav files in C:\WINDOWS and its subdirectories.
从技术上讲,你不必做两用FindFirstFile()调用,但我发现匹配函数Microsoft提供(即PathMatchFileSpec或其他)模式不一样能干,用FindFirstFile()。虽然为* .WAV它可能会被罚款。
Technically you don't have to do two FindFirstFile() calls, but I find the pattern matching functions Microsoft provides (i.e. PathMatchFileSpec or whatever) aren't as capable as FindFirstFile(). Though for "*.wav" it would probably be fine.
这篇关于如何递归遍历目录使用C在Windows的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!