我指的是this thread列出文件夹中的所有文件。这是功能:
vector<string> GetFileList(string path)
{
vector<string> names;
WIN32_FIND_DATA fd;
LPCSTR pathLPCW = path.c_str();
HANDLE hFind = ::FindFirstFile(pathLPCW, &fd);
if(hFind != INVALID_HANDLE_VALUE)
{
do
{
// read all (real) files in current folder
// , delete '!' read other 2 default folder . and ..
if(! (fd.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) )
{
string fileName(fd.cFileName);
names.push_back(fileName);
}
} while(::FindNextFile(hFind, &fd));
::FindClose(hFind);
}
return names;
}
以下是在main中调用它的方式:
int _tmain(int argc, _TCHAR* argv[])
{
string path = "D:\\CTData\\64_Slice_Data\\Helical\\fisrt_helical64_data";
vector<string> fileList = GetFileList(path);
return 0;
}
但是,我在列表中得到0个文件。当我调试时,我发现以下行对于if条件是假的。
if(! (fd.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) )
我不太明白为什么。我显然在文件夹中有文件。那么为什么我得到一个空列表呢?非常感谢。
更新
我在(:: FindNextFile(hFind,&amp; fd))之后添加了GetLastError();如下:
while(::FindNextFile(hFind, &fd));
lastError = GetLastError();
我发现ERROR_NO_MORE_FILES' (18)
错误。我很困惑,因为看起来我文件夹中有很多文件?
答案 0 :(得分:2)
您的问题是过滤器。基本上"D:\\CTData\\64_Slice_Data\\Helical\\fisrt_helical64_data"
指向目录本身。您需要将其更改为"D:\\CTData\\64_Slice_Data\\Helical\\fisrt_helical64_data\\*.*"
如果我正在写它,我也会避免返回一个向量并将指针传递给要填充的函数。
#include <Windows.h>
#include <vector>
#include <string>
using namespace std;
typedef vector<wstring> TFileList;
void GetFileList(wstring path, TFileList* pFileList)
{
WIN32_FIND_DATA fd;
HANDLE hFind = ::FindFirstFile(path.c_str(), &fd);
if (hFind != INVALID_HANDLE_VALUE)
{
do
{
// read all (real) files in current folder
// , delete '!' read other 2 default folder . and ..
if (!(fd.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY))
{
wstring fileName(fd.cFileName);
pFileList->push_back(fileName);
}
} while (::FindNextFile(hFind, &fd));
::FindClose(hFind);
}
}
int WINAPI wWinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPWSTR lpCmdLine, int nCmdShow)
{
wstring path = {L"D:\\CTData\\64_Slice_Data\\Helical\\fisrt_helical64_data\\*.*"};
TFileList names;
GetFileList(path, &names);
return 0;
}
想象一下你的函数是否返回1000个文件名。您不想创建一次列表,然后将其复制到新位置,然后删除函数内的列表。
同时将main
函数更改为新格式。
萨姆
答案 1 :(得分:1)
您最后必须使用通配符,来自MSDN documentation:
要检查不是根目录的目录,请使用该目录的路径,而不使用尾部反斜杠。例如,“C:\ Windows”的参数返回有关目录“C:\ Windows”的信息,而不是“C:\ Windows”中的目录或文件。要检查“C:\ Windows”中的文件和目录,请使用lpFileName“C:\ Windows \ *”。