gpt4 book ai didi

c - 使用 C 和 Windows 列出目录内容

转载 作者:可可西里 更新时间:2023-11-01 12:15:35 24 4
gpt4 key购买 nike

我希望在 Windows 上使用 C 列出目录的内容并将其存储在结构中。

我不一定要找任何人来写出我正在寻找的代码,而是在我应该查看哪个库时为我指明正确的方向。

我已经在谷歌上搜索了几个小时,我只找到了 C#、C++ 解决方案,因此非常感谢任何帮助。

最佳答案

就像其他人所说的那样(使用 FindFirstFile、FindNextFile 和 FindClose)...但是使用递归!

#include <windows.h>
#include <stdio.h>
#include <stdlib.h>

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 对应物:

#include <windows.h>
#include <stdio.h>
#include <stdlib.h>

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\\");

关于c - 使用 C 和 Windows 列出目录内容,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2314542/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com