C++獲取資料夾下具有特殊字尾的所有檔名(Ubuntu)
//用C++實現獲取某個檔案下,包含特殊字尾名的所有檔名
#include<iostream>
#include<vector>
#include<string.h> //包含strcmp的標頭檔案,也可用: #include <ctring>
#include<dirent.h>
void getFileNames(const std::string path, std::vector<std::string>& filenames, const std::string suffix = "")
{
DIR *pDir;
struct
if (!(pDir = opendir(path.c_str())))
return;
while ((ptr = readdir(pDir))!=0)
{
if (strcmp(ptr->d_name, ".") != 0 && strcmp(ptr->d_name, "..") != 0)
{
std::string file = path + "/" + ptr->d_name;
if (opendir(file.c_str()))
{
getFileNames(file, filenames, suffix);
}
else
{
if (suffix == file.substr(file.size() - suffix.size()))
{
filenames.push_back(file);
}
}
}
}
closedir(pDir);
}
//若需要獲取資料夾下的所有檔名,可以: 1) getFileNames(path, fileNames); 2) getFileNames(path, fileNames, "")