【发布时间】:2016-03-07 06:07:02
【问题描述】:
我正在用 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
【问题讨论】:
-
试过把 \* 放在路径的末尾吗?
标签: c++ windows file directory