Jump to content

Walk a directory/Recursively: Difference between revisions

No edit summary
Line 34:
</lang>
The solution first enumerates files in a directory, that includes the subdirectories, if their names match the pattern. Then it steps down into each of the subdirectories. The pseudo directories . and .. are excluded. The behavior upon symbolic links depends on the [[OS]] and the implementation of the Ada.Directories package.
 
=={{header|C}}==
{{works with|POSIX|.1-2001}}
This is a (recursive) ''extension'' of the code at [[Walk Directory]].
<lang c>#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
#include <dirent.h>
#include <regex.h>
#include <stdio.h>
 
#define MAXPD 1024
void walker(const char *dir, const char *pattern)
{
struct dirent *entry;
regex_t reg;
DIR *d;
struct stat fs;
static int indent = 0;
int i;
char pd[MAXPD];
 
if (regcomp(&reg, pattern, REG_EXTENDED | REG_NOSUB)) return;
if (!(d = opendir(dir))) return;
while (entry = readdir(d)) {
if ( ( strcmp(".", entry->d_name) == 0 ) ||
( strcmp("..", entry->d_name) == 0 ) ) continue;
if ( stat(entry->d_name, &fs) < 0 ) return;
if ( S_ISDIR(fs.st_mode) ) {
for(i=0; i < indent; i++) printf(" ");
puts(entry->d_name);
indent += 2;
if ( getcwd(pd, MAXPD) == NULL ) return;
if ( chdir(entry->d_name) < 0 ) return;
walker(".", pattern);
if ( chdir(pd) < 0 ) return;
indent -= 2;
} else {
if (!regexec(&reg, entry->d_name, 0, NULL, 0)) {
for(i=0; i < indent; i++) printf(" ");
puts(entry->d_name);
}
}
}
closedir(d);
}
 
int main()
{
walker(".", ".\\.c$");
return 0;
}</lang>
 
=={{header|D}}==
module std.file provides different walk directory functions (listdir).<br>
Cookies help us deliver our services. By using our services, you agree to our use of cookies.