4

Having a few issues trying to think of a good way to have a directory traverser that will only select wav files and return the strings for those files exclusively, e.g. just wav files. I can stop dirent.h looking in subdirectories, I'm pretty sure I just need an if statement that only allows files with .wav in string

So far my code looks like this, I just extended a few examples I've seen on the wiki page for the header file:

ifstream fin;
string dir, filepath;
DIR *dp;
struct dirent *dirp;
struct stat filestat;


cout << "dir to get files of: " << flush;

getline(cin, dir);

dp = opendir( dir.c_str() );

if (dp == NULL){

    cout << "Error(" << errno << ") opening " << dir << endl;

    }

while ((dirp = readdir( dp ))){

    filepath = dir + "/" + dirp->d_name;

    if (stat( filepath.c_str(), &filestat )) continue;
    if (S_ISDIR( filestat.st_mode ))         continue;

    fin.open( filepath.c_str() );

    stringVec.push_back(filepath);

    fin.close();

    }

closedir( dp );

for(int i=0;i<stringVec.size();i++){
    cout << stringVec[i] << endl;

}

Any help appreciated, I'm its not super difficult - but so far I haven't been able to figure it out.

Puppy
  • 144,682
  • 38
  • 256
  • 465
Rhys Davies
  • 69
  • 1
  • 9
  • Use http://stackoverflow.com/questions/874134/find-if-string-endswith-another-string-in-c to check if the filename ends with .wav – user786653 Apr 26 '12 at 15:03
  • Use `if (!S_ISREG(filestat.st_mode))`; your `.wav` files aren't sockets, character or block special devices, FIFOs, etc. After that, or even before any of the `stat`-based checks, check that the last 4 characters of the name are `.wav`. – Jonathan Leffler Apr 26 '12 at 15:43

1 Answers1

4

I have exactly the solution you're looking for on github.

paulrehkugler
  • 3,241
  • 24
  • 45
  • if (fname.find(extension, (fname.length() - extension.length())) != std::string::npos) Please check what will happen when the extension is greater than the fname length, because find i think takes a size_t which is unsigned... – Owl Sep 07 '18 at 10:00