我正在寻找在 Windows 上使用 C 的结构中列出和存储目录的内容。
我不一定要找人写出我正在寻找的代码,而是在我应该查看哪个库时为我指明正确的方向。
我已经在谷歌上搜索了几个小时,我发现的只是 C#、C++ 解决方案,因此我们将不胜感激。
我正在寻找在 Windows 上使用 C 的结构中列出和存储目录的内容。
我不一定要找人写出我正在寻找的代码,而是在我应该查看哪个库时为我指明正确的方向。
我已经在谷歌上搜索了几个小时,我发现的只是 C#、C++ 解决方案,因此我们将不胜感激。
就像其他人所说的(使用 FindFirstFile、FindNextFile 和 FindClose)......但使用递归!
bool ListDirectoryContents(const char *sDir)
{
WIN32_FIND_DATA fdFile;
HANDLE hFind = NULL;
char sPath[2048];
//Specify a file mask. *.* = We want everything!
sprintf(sPath, "%s\\*.*", sDir);
if((hFind = FindFirstFile(sPath, &fdFile)) == INVALID_HANDLE_VALUE)
{
printf("Path not found: [%s]\n", sDir);
return false;
}
do
{
//Find first file will always return "."
// and ".." as the first two directories.
if(strcmp(fdFile.cFileName, ".") != 0
&& strcmp(fdFile.cFileName, "..") != 0)
{
//Build up our file path using the passed in
// [sDir] and the file/foldername we just found:
sprintf(sPath, "%s\\%s", sDir, fdFile.cFileName);
//Is the entity a File or Folder?
if(fdFile.dwFileAttributes &FILE_ATTRIBUTE_DIRECTORY)
{
printf("Directory: %s\n", sPath);
ListDirectoryContents(sPath); //Recursion, I love it!
}
else{
printf("File: %s\n", sPath);
}
}
}
while(FindNextFile(hFind, &fdFile)); //Find the next file.
FindClose(hFind); //Always, Always, clean things up!
return true;
}
ListDirectoryContents("C:\\Windows\\");
现在它的 UNICODE 对应物:
bool ListDirectoryContents(const wchar_t *sDir)
{
WIN32_FIND_DATA fdFile;
HANDLE hFind = NULL;
wchar_t sPath[2048];
//Specify a file mask. *.* = We want everything!
wsprintf(sPath, L"%s\\*.*", sDir);
if((hFind = FindFirstFile(sPath, &fdFile)) == INVALID_HANDLE_VALUE)
{
wprintf(L"Path not found: [%s]\n", sDir);
return false;
}
do
{
//Find first file will always return "."
// and ".." as the first two directories.
if(wcscmp(fdFile.cFileName, L".") != 0
&& wcscmp(fdFile.cFileName, L"..") != 0)
{
//Build up our file path using the passed in
// [sDir] and the file/foldername we just found:
wsprintf(sPath, L"%s\\%s", sDir, fdFile.cFileName);
//Is the entity a File or Folder?
if(fdFile.dwFileAttributes &FILE_ATTRIBUTE_DIRECTORY)
{
wprintf(L"Directory: %s\n", sPath);
ListDirectoryContents(sPath); //Recursion, I love it!
}
else{
wprintf(L"File: %s\n", sPath);
}
}
}
while(FindNextFile(hFind, &fdFile)); //Find the next file.
FindClose(hFind); //Always, Always, clean things up!
return true;
}
ListDirectoryContents(L"C:\\Windows\\");
可能您正在寻找这些函数:FindFirstFile、FindNextFile和FindClose。
要列出文件内容,您可以使用以下 API 搜索目录:FindFirstFileEx、FindNextFile和CloseFind。您需要#include <windows.h>
,这将使您能够访问 Windows API。它们是 C 函数,因此与 C++ 兼容。如果您想要“特别是 C++”,请尝试使用 MFC 搜索列表目录。