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

C++ 如何将目录的特定文件名读入数组,c++,C++,我尝试将目录的所有文件名读入数组,我的代码成功地将整个文件名添加到数组中。然而,我需要它做的是 第一个是,不是所有的,只有以.cpp或.java结尾的特殊文件名。应该在这一部分完成,但我的比较不起作用。我该怎么做 DIR *dir; struct dirent *dirEntry; vector<string> dirlist; while ((dirEntry = readdir(dir)) != NULL) {

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

第一个是,不是所有的,只有以.cpp或.java结尾的特殊文件名。应该在这一部分完成,但我的比较不起作用。我该怎么做

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

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

我想这对你的案子很有用

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 );
}
参考:

#包括
#包括“boost/filesystem.hpp”
使用名称空间std;
使用名称空间boost::filesystem;
int main(int argc,char*argv[])
{
路径p(argv[1]);
目录\u迭代器end\u itr;
std::矢量文件名;
std::向量dirname;
for(目录迭代器itr(p);itr!=end\u itr;++itr)
{
如果(是常规文件(itr->path())
{
string file=itr->path().string();

什么类型,什么比较不起作用?你在为哪个操作系统编程?这取决于平台。很抱歉,我没有发布它。目录列表类型是vector。在windows上工作对我来说就足够了。Thanx man,我正在寻找strstr(hFile->d_name,.txt)这部分:d
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 );
}
#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);
    }
  }
}