如何读取目录中的所有文件?
在C#中,我会获取一个DirectoryInfo对象,并将所有文件存储在FileInfo[]对象中。
C++的STD命名空间中是否有类似的功能?
如果您需要一个免费、便携的解决方案,请尝试Boost文件系统库。
bool EnumDirectory( LPCTSTR szPath, std::vector<std::string>& rtList,
bool bIncludeDirs, bool bIncludeFiles )
{
HANDLE hFind;
WIN32_FIND_DATA FindFileData;
std::string strDirPath = ( szPath ) ? szPath : "";
// Throw on a trailing backslash if not included
if( !strDirPath.empty() && strDirPath[ strDirPath.length() - 1 ] != '\\' )
strDirPath += "\\";
// Looking for all files, so *
strDirPath += "*";
hFind = FindFirstFile( strDirPath.c_str(), &FindFileData );
if( hFind == INVALID_HANDLE_VALUE ) return false;
while( FindNextFile( hFind, &FindFileData ) )
{
if( !strcmp( FindFileData.cFileName, "." ) ||
!strcmp( FindFileData.cFileName, ".." ) ) continue;
if( FindFileData.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY )
{
if( bIncludeDirs ) rtList.push_back( FindFileData.cFileName );
}
else
{
if( bIncludeFiles ) rtList.push_back( FindFileData.cFileName );
}
}
FindClose( hFind );
return true;
}
使用boost文件系统库(正如其他人所提到的)。相同的API将在下一个标准库中,因此对于新项目来说,这肯定是最好的方法,除非您绝对需要它无法完成的某些任务。