如何获得给定文件夹中具有特定扩展名的文件的列表?
我想获得在给定文件夹中具有特定扩展名的所有文件的文件名(以及recursion的子文件夹)。 也就是文件名(和扩展名),而不是完整的文件path。 这在Python这样的语言中是非常简单的,但是我不熟悉C ++中的这个构造。 怎么办?
#define BOOST_FILESYSTEM_VERSION 3 #define BOOST_FILESYSTEM_NO_DEPRECATED #include <boost/filesystem.hpp> namespace fs = ::boost::filesystem; // return the filenames of all files that have the specified extension // in the specified directory and all subdirectories void get_all(const fs::path& root, const string& ext, vector<fs::path>& ret) { if(!fs::exists(root) || !fs::is_directory(root)) return; fs::recursive_directory_iterator it(root); fs::recursive_directory_iterator endit; while(it != endit) { if(fs::is_regular_file(*it) && it->path().extension() == ext) ret.push_back(it->path().filename()); ++it; } }
在Windows上你做这样的事情:
void listFiles( const char* path ) { struct _finddata_t dirFile; long hFile; if (( hFile = _findfirst( path, &dirFile )) != -1 ) { do { if ( !strcmp( dirFile.name, "." )) continue; if ( !strcmp( dirFile.name, ".." )) continue; if ( gIgnoreHidden ) { if ( dirFile.attrib & _A_HIDDEN ) continue; if ( dirFile.name[0] == '.' ) continue; } // dirFile.name is the name of the file. Do whatever string comparison // you want here. Something like: if ( strstr( dirFile.name, ".txt" )) printf( "found a .txt file: %s", dirFile.name ); } while ( _findnext( hFile, &dirFile ) == 0 ); _findclose( hFile ); } }
在Posix上,像Linux或OsX:
void listFiles( const char* path ) { DIR* dirFile = opendir( path ); if ( dirFile ) { struct dirent* hFile; errno = 0; while (( hFile = readdir( dirFile )) != NULL ) { if ( !strcmp( hFile->d_name, "." )) continue; if ( !strcmp( hFile->d_name, ".." )) continue; // in linux hidden files all start with '.' if ( gIgnoreHidden && ( hFile->d_name[0] == '.' )) continue; // dirFile.name is the name of the file. Do whatever string comparison // you want here. Something like: if ( strstr( hFile->d_name, ".txt" )) printf( "found an .txt file: %s", hFile->d_name ); } closedir( dirFile ); } }
获取文件列表并处理每个文件并通过它们循环并存储回不同的文件夹
void getFilesList(string filePath,string extension, vector<string> & returnFileName) { WIN32_FIND_DATA fileInfo; HANDLE hFind; string fullPath = filePath + extension; hFind = FindFirstFile(fullPath.c_str(), &fileInfo); if (hFind != INVALID_HANDLE_VALUE){ returnFileName.push_back(filePath+fileInfo.cFileName); while (FindNextFile(hFind, &fileInfo) != 0){ returnFileName.push_back(filePath+fileInfo.cFileName); } } }
USE:你可以像这样使用从文件夹中加载所有的文件,并逐个循环
String optfileName =""; String inputFolderPath =""; String extension = "*.jpg*"; getFilesList(inputFolderPath,extension,filesPaths); vector<string>::const_iterator it = filesPaths.begin(); while( it != filesPaths.end()) { frame = imread(*it);//read file names //doyourwork here ( frame ); sprintf(buf, "%s/Out/%d.jpg", optfileName.c_str(),it->c_str()); imwrite(buf,frame); it++; }
你不说你在哪个操作系统,但有几个选项。
正如评论者所说, boost :: filesystem将工作,如果你可以使用boost。
其他选项是
- 使用MFC的CFileFind类
- FindFirstFile / FindNextFile与WIN32
- opendir / readdir与POSIX 。