如何获取目录中的所有文件名
How can I obtain all of the file names in a directory?
我正在用C++编写一个程序。我正在尝试获取程序可执行文件所在的文件夹中的所有文件,并将它们存储在矢量中。有人告诉我,以下代码应该可以工作,但 FindFirstFile 操作只找到一个文件(它应该搜索的文件夹的名称(。如何更改代码以使其正确查看文件夹?
std::vector<char*> fileArray;
//Get location of program executable
HMODULE hModule = GetModuleHandleW(NULL);
WCHAR path[MAX_PATH];
GetModuleFileNameW(hModule, path, MAX_PATH);
//Remove the executable file name from 'path' so that it refers to the folder instead
PathCchRemoveFileSpec(path, sizeof(path));
//This code should find the first file in the executable folder, but it fails
//Instead, it obtains the name of the folder that it is searching
WIN32_FIND_DATA ffd;
HANDLE hFind = INVALID_HANDLE_VALUE;
hFind = FindFirstFile(path, &ffd);
do
{
//The name of the folder is pushed onto the array because of the previous code's mistake
//e.g. If the folder is "C:\MyFolder", it stores "MyFolder"
fileArray.push_back(ffd.cFileName); //Disclaimer: This line of code won't add the file name properly (I'll get to fixing it later), but that's not relevant to the question
} while (FindNextFile(hFind, &ffd) != 0); //This line fails to find anymore files
有人告诉我以下代码应该可以工作
你被告知错了,因为你提供的代码被严重破坏了。
FindFirstFile 操作仅查找一个文件(应搜索的文件夹的名称(。
您只是将文件夹路径本身传递给FindFirstFile()
,因此只会报告一个条目,描述文件夹本身。 您需要做的是在路径末尾附加一个*
或*.*
通配符,然后FindFirstFile()
/FindNextFile()
将枚举文件夹中的文件和子文件夹。
除此之外,代码还有其他几个问题。
即使枚举有效,也不会区分文件和子文件夹。
您正在将错误的值传递给 PathCchRemoveFileSpec()
的第二个参数。 您正在传入字节计数,但它需要字符计数。
您没有在进入循环之前检查FindFirstFile()
是否失败,也没有在循环完成后调用FindClose()
。
最后,您的代码甚至不会按原样编译。 您的vector
存储char*
值,但是为了将WCHAR[]
传递给FindFirstFile()
,必须定义UNICODE
,这意味着FindFirstFile()
将映射到FindFirstFileW()
,WIN32_FIND_DATA
将映射到WIN32_FIND_DATAW
,因此cFileName
字段将是一个WCHAR[]
。 编译器不允许将WCHAR[]
(或WCHAR*)
分配给char*
。
尝试更多类似的东西:
std::vector<std::wstring> fileArray;
//Get location of program executable
WCHAR path[MAX_PATH+1] = {0};
GetModuleFileNameW(NULL, path, MAX_PATH);
//Remove the executable file name from 'path' so that it refers to the folder instead
PathCchRemoveFileSpec(path, MAX_PATH);
// append a wildcard to the path
PathCchAppend(path, MAX_PATH, L"*.*");
WIN32_FIND_DATAW ffd;
HANDLE hFind = FindFirstFileW(path, &ffd);
if (hFile != INVALID_HANDLE_VALUE)
{
do
{
if ((ffd.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) == 0)
fileArray.push_back(ffd.cFileName);
}
while (FindNextFileW(hFind, &ffd));
FindClose(hFind);
}
- 从 Makefile 中的 $@ 获取文件名
- 有没有一种简单的方法可以从 c++ 中的路径获取文件名?
- C++获取当前文件名并在 WinExec 上使用它
- 从 SetClipboardData 挂钩获取文件名
- 从 QFileSystemModel 中的文件路径和文件名获取 QModelIndex
- 获取打开文件名 - 预选上次打开不起作用
- 获取模块文件名 Win 7/Win 10 上的不同行为
- 如何通过键入文件名来获取文件的目录。(C++)
- 获取 Qt 标签图像的文件名
- LLVM 如何获取调用站点文件名和行号
- 如何在C++中获取可执行文件名
- C++ ( MS V S ) 获取打开文件名
- 运行正则表达式时未选中的异常 - 从文件路径获取不带扩展名的文件名
- 获取打开文件名在默认目录打开'Computer'可能吗?
- 是否有一种便携式/标准的方法可以在堆栈跟踪中获取文件名和亚麻布
- 如何从文件夹中获取文件名,并将它们添加到QT中的孩子中
- 从 Windows 上的 tmpfile() 获取文件名
- 如何在c++中从shell中获取作为输入重定向的文件名
- 在 QFile::set文件名上获取分段错误
- 如何从DLL的文件名中获取进程ID (windows)