1. 程式人生 > 其它 >C++實現迴圈查詢某一格式的檔案

C++實現迴圈查詢某一格式的檔案

技術標籤:C++應用c++

我們經常回遇到需要在某個目錄檔案下面查詢某種格式的檔案。之前寫的一個c++函式:

//查詢.json檔案
void CgetH264AAC::findJsonFile(char *dir_name)
{
	std::stringstream stream;
	// check the parameter !
	if( NULL == dir_name )
	{
		std::cout<<" dir_name is null ! "<<std::endl;
		return;
	}
	// check if dir_name is a valid dir
struct stat s; lstat( dir_name , &s ); if( ! S_ISDIR( s.st_mode ) ) { std::cout<<"dir_name is not a valid directory !"<<std::endl; return ; } struct dirent * filename; // return value for readdir() DIR * dir; // return value for opendir() dir = opendir( dir_name )
; if( NULL == dir ) { printf("Can not open dir \n"); return ; } //printf("Successfully opened the dir ! \n"); /* read all the files in the dir ~ */ while( ( filename = readdir(dir) ) != NULL ) { // get rid of "." and ".." if( strcmp( filename->d_name ,
"." ) == 0 || strcmp( filename->d_name , "..") == 0 ) continue ; else if(filename->d_type == 8 || filename->d_type == 10)//file OR link file { stream.str(""); stream<<dir_name<<"/"<<filename->d_name; if(stream.str().substr(stream.str().size()-5,5) == ".json") { //std::cout<<stream.str().substr(0,stream.str().size()-5)<<std::endl; //repairpath.push_back("asdasfafa"); repairpath.push_back(stream.str().substr(0,stream.str().size()-5)); } } } dir=opendir(dir_name); while ((filename=readdir(dir))!=NULL){ if(strcmp(filename->d_name,".")==0 || strcmp(filename->d_name,"..")==0)//current dir OR parrent dir continue; else if(filename->d_type == 4){//dir stream.str(""); stream<<dir_name<<"/"<<filename->d_name; findJsonFile(stream.str().c_str()); } } closedir(dir); }