如何将目录的特定文件名读入数组

时间:2015-06-12 12:13:58

标签: c++

我尝试将目录的所有文件名读入数组,我的代码成功将整个文件名添加到数组中。但是,我需要它做什么,

第一个是获取,而不是全部,只有特定的文件名,如.cpp或.java。它应该在这部分完成,我的比较不起作用。我怎么能这样做?

DIR           *dir;
struct dirent *dirEntry;
vector<string> dirlist;  

while ((dirEntry = readdir(dir)) != NULL)
            {
                   //here
                       dirlist.push_back(dirEntry->d_name);
            }

2dn one从用户获取目录位置。我也不能这样做,它只有在我写位置地址时才有效,我如何从用户获取位置来获取文件?

dir = opendir(//here);

2 个答案:

答案 0 :(得分:0)

我认为这适合你的情况,

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

参考:How to get list of files with a specific extension in a given folder

答案 1 :(得分:0)

#include <iostream>
#include "boost/filesystem.hpp"

using namespace std;
using namespace boost::filesystem;

int main(int argc, char *argv[])
{
  path p (argv[1]);

  directory_iterator end_itr;

  std::vector<std::string> fileNames;
  std::vector<std::string> dirNames;


  for (directory_iterator itr(p); itr != end_itr; ++itr)
  {
    if (is_regular_file(itr->path()))
    {
      string file = itr->path().string();
      cout << "file = " << file << endl;
      fileNames.push_back(file);
    }
    else if (is_directory(itr->path()))
    {
      string dir = itr->path().string();
      cout << "directory = " << dir << endl;
      dirNames.push_back(dir);
    }
  }
}