OpenCV獲取資料夾下所有檔名
一、OpenCV中有實現遍歷資料夾下所有檔案的類Directory,它裡面包括3個成員函式:(1)、GetListFiles:遍歷指定資料夾下的所有檔案,不包括指定資料夾內的資料夾;(2)、GetListFolders:遍歷指定資料夾下的所有資料夾,不包括指定資料夾下的檔案;(3)、GetListFilesR:遍歷指定資料夾下的所有檔案,包括指定資料夾內的資料夾。
若要使用Directory類,則需包含contrib.hpp標頭檔案,此類的實現在contrib模組。
string path1 = "E:\\程式碼轉化\\synopsis\\座標資訊2"
string exten1 = "*.txt";
bool addPath1 = false;
vector<string> filenames = dir.GetListFiles(path1, exten1, addPath1);
注:這樣獲得的 filenames中,只儲存 資料夾 path1 下的檔名,不是全部路徑;
下面的程式碼可以獲得 path1 下的檔案的完整的路徑 ;
但是兩者儲存的順序都很奇怪:例如path1下有12個txt檔案,則輸出後的順序都是:1.txt,10.txt,11.txt,12.txt,2.txt,3.txt等等
二、
void GetAllFileInfo(char* path, vector<char*> &filesPathVector)
{
//find the first file
_tfinddata_t c_file;
intptr_t hFile;
char root[MAX_PATH];
strcpy(root,path);
strcat(root,"\\*.*");
hFile=_tfindfirst(CA2CT(root),&c_file);
if( hFile == -1)
return;
//search all files recursively.
do
{
if(_tcslen(c_file.name)==1&&c_file.name[0]==_T('.')
||_tcslen(c_file.name)==2&&c_file.name[0]==_T('.')&&c_file.name[1]==_T('.'))
continue;
char* fullPath=new char[MAX_PATH];
strcpy(fullPath,path);
strcat(fullPath,"\\");
char* name=(char*)malloc(2*wcslen(c_file.name)+1);
wcstombs(name,c_file.name,2*wcslen(c_file.name)+1);
strcat(fullPath,name);
if(c_file.attrib&_A_SUBDIR)
{
GetAllFileInfo(fullPath,filesPathVector);
}
else
{
//store full file path in vector.
//char pr=*fullPath;
filesPathVector.push_back(fullPath);
//print file info
}
}
while( _tfindnext( hFile, &c_file ) == 0);
//close search handle
_findclose(hFile);
}