在windows操作系统下可以使用微软的文件查找功能_findfirst(或_findfirsti64) 和_findnext(或者_findnexti64)配合_finddata_t(或者_finddatai64_t),但是无法脱离windows使用。
如果需要使用宽字符的查找,可以在下划线后加入w(如_wfindfirst)。
使用boost的FileSystem可以摆脱系统关联,so,查找文件夹的代码如下。
#include
#include
#include
using namespace boost::filesystem;
void GetFolders(std::vector<std::wstring> & folders, const wchar_t * folders_path)
{
path p(folders_path);
try
{
if (exists(p))
{
if (is_directory(p))
{
directory_iterator iter_end;
for (directory_iterator iter(p); iter != iter_end; ++iter)
{
std::wstring dir_wname = (*iter).path().wstring();
std::wstring file_wname = (*iter).path().filename().wstring();
if (is_directory(*iter))
{
folders.push_back(dir_wname);
}
GetFolders(folders, dir_wname.c_str());
}
}
}
else
{
return;
}
}
catch (const filesystem_error& ex)
{
std::wcout << L"Error!!" << std::endl;
}
}
void main()
{
const wchar_t * my_path = L"D:\\test_data";
std::vector folders;
GetFolders(folders, my_path);
for(auto& folder : folders)
{
std::wcout << folder.c_str() << std::endl;
}
std::system("pause");
}
如果需要查找文件名可以使用函数:
bool boost::filesystem::is_regular_file(boost::filesystem::path &p);
替代文件夹查找:
bool boost::filesystem::is_directory(boost::filesystem::path &p);