Monday 29 February 2016

Finding all files of a given extension from a directory in C++

I have just found this useful recently and my blog it's a nice place to back it up for future reference. :)
The following small script takes as input an extension and a directory and prints all the files inside that directory that have that extension.


#include < iostream >
#include< stdio.h >
#include< cstdlib >
#include< iostream >
#include< string .h >
#include< fstream >
#include< sstream >
#include< dirent .h >
#include < vector >
// < extension > < directory >
int main(int argc, char *argv[])
{
    if(argc!=3)
    {
       std::cerr << "Too few arguments. Please include the following\n"
                 << "<.extension> \n";
       return EXIT_FAILURE;
    }
    std::string  dirStr(argv[2]);
    std::string extension(argv[1]);
    DIR *dir;
    struct dirent *ent;
    unsigned int count(0);
    if ((dir = opendir (dirStr.c_str())) != NULL) {
      /* print all the files and directories within directory */
      while ((ent = readdir (dir)) != NULL)
      {
        std::string current(ent->d_name);
        if(current.size()>extension.size())
        {
           std::string ext = current.substr(current.length()-extension.length());
           if(ext==extension)
           {
              std::cout << current << "\n";
              count++;
           }
        }
      }
    }
    std::cout << count << " files with extension " << extension << " found\n";
    std::cout << "   ***   EXIT   ***\n";
    return EXIT_SUCCESS;
}