Davidwy
asked on
Search a directory for certain files
Hello,
I need to recursively search a local directory for all files ending with ".tgz" Can anybody tell me how to do this?
Any ideas are highly appreciated.
Thanks,
David
I need to recursively search a local directory for all files ending with ".tgz" Can anybody tell me how to do this?
Any ideas are highly appreciated.
Thanks,
David
ASKER CERTIFIED SOLUTION
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
// set the directory where you are looking for files as the current one
if (!_chdir("c:\\search"))
// something wrong
struct _finddata_t c_file;
long hFile;
if ((hFile = _findfirst( "*.tgz", &c_file )) == -1)
// no files were found
else
{
// find the first file
// c_file.name contains the file name
// looking for others
while(!_findnext(hFile, &c_file))
{
// find the next file
// c_file.name contains the file name
}
// don't fordet to release a handle
_findclose(hFile);
}
if (!_chdir("c:\\search"))
// something wrong
struct _finddata_t c_file;
long hFile;
if ((hFile = _findfirst( "*.tgz", &c_file )) == -1)
// no files were found
else
{
// find the first file
// c_file.name contains the file name
// looking for others
while(!_findnext(hFile, &c_file))
{
// find the next file
// c_file.name contains the file name
}
// don't fordet to release a handle
_findclose(hFile);
}
ASKER
HelloJkr and YurPutivsky,
As I work on Linux, I accept Jkr's comment as my answer. Thanks to you all for your comments!
Regards,
David
As I work on Linux, I accept Jkr's comment as my answer. Thanks to you all for your comments!
Regards,
David
#include <sys/types.h>
#include <dirent.h>
#include <string>
#include <iostream>
using namespace std;
bool search_for_file ( const string& sStartDir, const string& sFile, string& sFound) {
cout << "checking " << sStartDir.c_str () << endl;
DIR* pDir = opendir ( sStartDir.c_str ());
if ( !pDir) return false;
dirent* pEntry;
while ( pEntry = readdir ( pDir)) {
cout << "found " << pEntry->d_name << endl;
if ( DT_DIR & pEntry->d_type && strcmp ( pEntry->d_name, ".") && strcmp ( pEntry->d_name, "..")) {
string sSubDir = sStartDir + string ( "/") + string ( pEntry->d_name);
if ( search_for_file ( sSubDir, sFile, sFound)) {
return true;
}
}
// does the file match?
if ( !strcmp ( pEntry->d_name, sFile.c_str ())) {
sFound = sStartDir + string ( "/") + string ( pEntry->d_name);
return true;
}
}
return false;
}
int main () {
string sFound = "notfound";
search_for_file ( ".", "thefile", sFound);
cout << sFound.c_str ();
}