あるフォルダ内のファイルを列挙するコード
MFC v_tstring EnumFiles_MFC (c_tstring& path,const bool skipDot=true) { v_tstring foundFiles ; { iFileFind ff ; BOOL isWorking = ff.FindFile((::Path_AddLastSP(path)+_T("*.*")).c_str()) ; while (isWorking) { isWorking = ff.FindNextFile() ; if (skipDot && ff.IsDots()) { continue ; } tstring fileName = ff.GetFileName() ; if (ff.IsDirectory()) { fileName = ::Path_AddLastSP(fileName) ; } foundFiles.push_back(::Path_AddLastSP(path)+fileName) ; } } return foundFiles ; }
MSC v_tstring EnumFiles_MSC (c_tstring& path,const bool skipDot=true) { v_tstring foundFiles ; { tstring fffPath = ::Path_AddLastSP(path)+_T("*.*") ; WIN32_FIND_DATA fd ; memset(&fd,0,sizeof(WIN32_FIND_DATA)) ; HANDLE hFind = ::FindFirstFile(fffPath.c_str(),&fd) ; if (hFind != INVALID_HANDLE_VALUE) { while (TRUE) { tstring fileName = fd.cFileName ; if (skipDot) { if (fileName == _T(".")) { fileName = _T("") ; } if (fileName == _T("..")) { fileName = _T("") ; } } if (!fileName.empty()) { if (fd.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) { fileName = ::Path_AddLastSP(fileName) ; } foundFiles.push_back(::Path_AddLastSP(path)+fileName) ; } if (!::FindNextFile(hFind,&fd)) { break ; } } ::FindClose(hFind) ; } } return foundFiles ; }
GNUC v_tstring EnumFiles_GNUC (c_tstring& path_,const bool skipDot=true) { tstring path = path_ ; v_tstring foundFiles ; { DIR* dp = ::opendir(path.c_str()) ; struct dirent* dent = NULL ; do { dent = readdir(dp) ; if (dent != NULL) { tstring fileName = dent->d_name ; if (skipDot) { if (fileName == _T(".")) { continue ; } if (fileName == _T("..")) { continue ; } } if (dent->d_type & DT_DIR) { fileName = ::Path_AddLastSP(fileName) ; } foundFiles.push_back(::Path_AddLastSP(path)+fileName) ; } } while (dent != NULL) ; ::closedir(dp) ; } return foundFiles ; }
MFC 版で,iFileFind としているのは,VC 6 MFC MBCS 版でのバグのため.
class iFileFind : public CFileFind { public: virtual CString GetFilePath() const { ASSERT(m_hContext != NULL); ASSERT_VALID(this); CString strResult = m_strRoot; #ifdef ____VC_6_______MBCS_BUG___ { if (strResult[strResult.GetLength()-1] != '\\' && strResult[strResult.GetLength()-1] != '/') { strResult += m_chDirSeparator; } } #else { LPCTSTR pszResult; LPCTSTR pchLast; pszResult = strResult; pchLast = _tcsdec( pszResult, pszResult+strResult.GetLength() ); VERIFY(pchLast!=NULL); if ((*pchLast != _T('\\')) && (*pchLast != _T('/'))) { strResult += m_chDirSeparator; } } #endif strResult += GetFileName(); return strResult; } } ;
MFC 7 以降であれば,CFileFind として利用可能.