如何将目录的特定文件名读取到数组中

How to read specific file names of a directory into an array

本文关键字:读取 文件名 数组      更新时间:2023-10-16

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

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

DIR           *dir;
struct dirent *dirEntry;
vector<string> dirlist;  
while ((dirEntry = readdir(dir)) != NULL)
            {
                   //here
                       dirlist.push_back(dirEntry->d_name);
            }

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

dir = opendir(//here);

我认为这对您的情况有用,

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