Walk a directory/Non-recursively: Difference between revisions

From Rosetta Code
Content added Content deleted
(add Common Lisp example)
No edit summary
Line 154: Line 154:
echo "$file\n";
echo "$file\n";
}
}

==[[Pop11]]==
[[Category:Pop11]]

Builtin procedure sys_file_match searches directories (or directory trees)
using shell-like patterns:

lvars repp, fil;
;;; create path repeater
sys_file_match('*.p', '', false, 0) -> repp;
;;; iterate over files
while (repp() ->> fil) /= termin do
;;; print the file
printf(fil, '%s\n');
endwhile;


==[[Tcl]]==
==[[Tcl]]==

Revision as of 20:14, 14 May 2007

Task
Walk a directory/Non-recursively
You are encouraged to solve this task according to the task description, using any language you may know.
This task has been clarified. Its programming examples are in need of review to ensure that they still fit the requirements of the task.


Walk a given directory and print the names of files matching a given pattern.

Note: This task is for non-recursive methods. These tasks should read a single directory, not an entire directory tree. For a code examples that read entire directory trees, see Walk Directory Tree

Note: Please be careful when running any code presented here.

Ada

Compiler: GCC 4.12

with Ada.Directories; use Ada.Directories;
with Ada.Text_IO; use Ada.Text_IO;

procedure Walk_Directory
            (Directory : in String := ".";
             Pattern   : in String := "") -- empty pattern = all file names/subdirectory names
is
   Search  : Search_Type;
   Dir_Ent : Directory_Entry_Type;
begin
   Start_Search (Search, Directory, Pattern);

   while More_Entries (Search) loop
      Get_Next_Entry (Search, Dir_Ent);
      Put_Line (Simple_Name (Dir_Ent));
   end loop;

   End_Search (Search);
end Walk_Directory;

C

Compiler: GCC 4.0.1

Platform: BSD

In this example, the pattern is a POSIX extended regular expression.

#include <sys/types.h>
#include <dirent.h>
#include <regex.h>
#include <stdio.h>

void walker(const char *dir, const char *pattern)
{
    struct dirent *entry;
    regex_t reg;
    DIR *d; 

    if (regcomp(&reg, pattern, REG_EXTENDED | REG_NOSUB))
        return;
    if (!(d = opendir(dir)))
        return;
    while (entry = readdir(d))
        if (!regexec(&reg, entry->d_name, 0, NULL, 0))
            puts(entry->d_name);
    closedir(d);
}

int main()
{
    walker(".", ".\\.c$");
    return 0;
}

C#

Compiler: MSVS 2005

 foreach( string file in Directory.GetFiles( @"c:\temp", @"*.txt" ) )
   System.Console.WriteLine( file );

ColdFusion

This example display all files and directories directly under C:\temp that end with .html

<cfdirectory action="list" directory="C:\temp" filter="*.html" name="dirListing">
<cfoutput query="dirListing">
  #dirListing.name# (#dirListing.type#)<br>
</cfoutput>

Common Lisp

(defun walk-directory (directory pattern)
  (directory (merge-pathnames pattern directory)))

Uses the filename pattern syntax provided by the CL implementation.

Haskell

Interpreter: GHCi 6.6

In this example, the pattern is a POSIX extended regular expression.

import System.Directory
import Text.Regex

walk :: FilePath -> String -> IO ()
walk dir pattern = do
    filenames <- getDirectoryContents dir
    putStr $ unlines $ filter ((/= Nothing).(matchRegex $ mkRegex pattern)) filenames

main = walk "." ".\\.hs$"


IDL

 f = file_search('*.txt', count=cc)
 if cc gt 0 then print,f

(IDL is an array language - very few things are ever done in 'loops'.)

Perl

Interpreter: Perl

my @files = FindFiles('/home/user/music/', 'sql');
print "$_\n" for (@files);

sub FindFiles($ $){
  my $dir = shift;
  my $match = shift;

  opendir(DIR, $dir);
  my @files = grep(/$match/, readdir(DIR));
  closedir(DIR);

  return(@files);
}

PHP

Interpreter: PHP 5.2.0

$pattern = 'php';
$dh = opendir('c:/foo/bar'); // Or '/home/foo/bar' for Linux
while (false !== ($file = readdir($dh)))
{
    if ($file != '.' and $file != '..')
    {
        if (preg_match("/$pattern/", $file))
        {
            echo "$file matches $pattern\n";
        }
    }
}

PHP

Interpreter: PHP 4 >= 4.3.0, PHP 5

foreach (glob('/home/foo/bar/*.php') as $file){
    echo "$file\n";
}

Pop11

Builtin procedure sys_file_match searches directories (or directory trees) using shell-like patterns:

lvars repp, fil;
;;; create path repeater
sys_file_match('*.p', , false, 0) -> repp;
;;; iterate over files
while (repp() ->> fil) /= termin do
     ;;; print the file
     printf(fil, '%s\n');
endwhile;

Tcl

 foreach var [glob *.txt] { puts $var }