0

I tried to read all file names of a directory into array and my code successfully addes whole file names into array. However, what i need it to do,

1st one is getting ,not all of them, only spesific file names which end like .cpp or .java. It should be done in this part and my comparisons did not work. How can i do that ?

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

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

2dn one is getting the directory location from user. I couldn't do that also, it only works if i write the location adress, how can i get location from user to get files ?

dir = opendir(//here);
donanimsal
  • 15
  • 4

2 Answers2

0

I think this would work for your case,

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

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

Community
  • 1
  • 1
Adeel Ahmed
  • 1,591
  • 8
  • 10
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);
    }
  }
}
Jerry
  • 35
  • 8