#include <dirent.h>
#include <sys/stat.h>
long findfileinfolder(const char * dir_name, string extend_name)//文件路径
{
// char dir[100] = "/home";
// int const MAX_STR_LEN = 200;
long number = 0;
// check the parameter !
if( NULL == dir_name )
{
cout<<" dir_name is null ! "<<endl;
return 0;
}
// check if dir_name is a valid directory
struct stat s;
lstat( dir_name , &s );
// if( ! S_ISDIR( s.st_mode ) )
// {
// cout<<"dir_name is not a valid directory !"<<endl;
// return 0;
// }
struct dirent * filename; // return value for readdir()
DIR * dir; // return value for opendir()
dir = opendir( dir_name );
if( NULL == dir )
{
cout<<"Can not open dir "<<dir_name<<endl;
return 0;
}
// cout<<"Successfully opened the dir !"<<endl;
/* 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;
string sFilename(filename->d_name);
string suffixStr = sFilename.substr(sFilename.find_last_of('.') + 1);//获取文件后缀
if (suffixStr.compare(extend_name) == 0) {//根据后缀筛选文件
cout<<filename ->d_name <<endl;
++number;
}
}
return number;
}
C++ 获取Ubuntu某一文件夹下特定后缀文件
最新推荐文章于 2023-03-13 16:16:07 发布