Linux/Winndow通用枚举目录下的文件C++实现
int enum_file_list(std::map<std::string, std::string>& map_file_list, const std::string& top_dir, const std::string&extension=".png")
{
std::string tdir = top_dir;
if (*tdir.rbegin() != '/')
{
tdir.append("/");
}
#ifdef _MSC_VER
WIN32_FIND_DATA filedata = { 0 };
HANDLE hFind = FindFirstFileExA((tdir + "*").c_str(), FindExInfoStandard, &filedata, FindExSearchNameMatch, NULL, 0);
if (hFind == INVALID_HANDLE_VALUE)
{
printf("Can not open dir %s\n", tdir.c_str());
return (-1);
}
while (FindNextFileA(hFind, &filedata) != 0)
{
if (strcmp(filedata.cFileName, ".") == 0 || strcmp(filedata.cFileName, "..") == 0)
{
continue;
}
if ((filedata.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) != FILE_ATTRIBUTE_DIRECTORY)
{
if (strstr(filedata.cFileName, extension.c_str()) != NULL)
{
map_file_list.emplace(filedata.cFileName, tdir + filedata.cFileName);
}
}
}
FindClose(hFind);
#else
DIR* dir = NULL;
struct dirent* filedata = NULL;
dir = opendir(tdir.c_str());
if (NULL == dir)
{
printf("Can not open dir %s\n", tdir.c_str());
return (-1);
}
// read all the files in the dir ~
while ((filedata = readdir(dir)) != NULL)
{
// get rid of "." and ".."
if (strcmp(filedata->d_name, ".") == 0 || strcmp(filedata->d_name, "..") == 0)
{
continue;
}
if ((filedata->d_type& DT_DIR) != DT_DIR)
{
if (strstr(filedata->d_name, extension.c_str()) != NULL)
{
map_file_list.emplace(filedata->d_name, tdir + filedata->d_name);
}
}
}
closedir(dir);
#endif
return 0;
}