如何获取给定文件夹中具有特定扩展名的文件列表

How to get list of files with a specific extension in a given folder?

本文关键字:扩展名 列表 文件 文件夹 何获取 获取      更新时间:2023-10-16

我想获取给定文件夹(递归地,其子文件夹)中具有特定扩展名的所有文件的文件名。 即文件名(和扩展名),而不是完整的文件路径。 这在像 Python 这样的语言中非常简单,但我不熟悉 C++ 中的结构。 怎么能做到呢?

#define BOOST_FILESYSTEM_VERSION 3
#define BOOST_FILESYSTEM_NO_DEPRECATED 
#include <boost/filesystem.hpp>
namespace fs = boost::filesystem;
/**
 * brief   Return the filenames of all files that have the specified extension
 *          in the specified directory and all subdirectories.
 */
std::vector<fs::path> get_all(fs::path const & root, std::string const & ext)
{
    std::vector<fs::path> paths;
    if (fs::exists(root) && fs::is_directory(root))
    {
        for (auto const & entry : fs::recursive_directory_iterator(root))
        {
            if (fs::is_regular_file(entry) && entry.path().extension() == ext)
                paths.emplace_back(entry.path().filename());
        }
    }
    return paths;
}             

a C++17 代码

#include <fstream>
#include <iostream>
#include <filesystem>
namespace fs = std::filesystem;
int main()
{
    std::string path("/your/dir/");
    std::string ext(".sample");
    for (auto &p : fs::recursive_directory_iterator(path))
    {
        if (p.path().extension() == ext)
            std::cout << p.path().stem().string() << 'n';
    }
    return 0;
}

在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);
        }
    }
}

使用:您可以像这样使用加载文件夹中的所有文件并逐个循环访问

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,boost::filesystem将起作用。

其他选项包括

  • CFileFind Class with MFC
  • FindFirstFile/FindNextFile with WIN32
  • opendir/readdir with POSIX.

这是我的解决方案(适用于 *nix 系统):

#include <dirent.h>
bool FindAllFiles(std::string path, std::string type, std::vector<std::string> &FileList){
  DIR *dir;
  struct dirent *ent;
  FileList.clear();
  if ((dir = opendir (path.c_str())) != NULL) {
    //Examine all files in this directory
    while ((ent = readdir (dir)) != NULL) {
      std::string filename = std::string(ent->d_name);
      if(filename.length() > 4){
        std::string ext = filename.substr(filename.size() - 3);
        if(ext == type){
          //store this file if it's correct type
          FileList.push_back(filename);
        }
      }
    }
    closedir (dir);
  } else {
    //Couldn't open dir
    std::cerr << "Could not open directory: " << path << "n";
    return false;
  }
  return true;
}

显然,将所需的扩展名更改为您喜欢的任何扩展名。还假定 3 个字符的类型。