Beefy Boxes and Bandwidth Generously Provided by pair Networks
Welcome to the Monastery
 
PerlMonks  

How do I read all the file names of a directory into an array?

( #45928=categorized question: print w/ replies, xml ) Need Help??
Contributed by Ri-Del on Dec 10, 2000 at 12:59 UTC
Q&A  > files


Description:

I would like to read the names of all the files in a directory of mine into an array so that I can convert each file name into a link to that file. Currently I am doing this in the following manner. I read the "dir.dat" file with the following command, "ls > dir.dat." I should like rather to get the current directory's files from within the script rather than having to do that command everytime I want to regenerate the html. How might I do this?
#!/usr/local/bin/perl use strict; @filename; $i = 0; $total; open(INFILE,"dir.dat"); while($filename[$i] = <INFILE>){ chop($filename[$i]); $filename[$i] =~ s/\*//g; $i++; $total++; } $error = open(OUTFILE,"> dict.html"); if(!$error){ print("ERROR\n"); exit(0); } print(OUTFILE "<HTML>\n <HEAD>\n </HEAD>\n <BODY TEXT=#00ff00 LINK=# +00ff00 VLINK=#00ff00 BGCOLOR=#000000 alink=00FF00>\n"); for($i=0;$i<=$total;$i++){ print(OUTFILE "<A HREF=\"$filename[$i]\">$filename[$i]</A><BR>\n"); } print(OUTFILE "</BODY>\n</HTML>\n"); close(OUTFILE);

Answer: How do I read all the file names of a directory into an array?
contributed by mirod

Use the directory functions: opendir, closedir and readdir.

opendir DIR, $dir or die "cannot open dir $dir: $!"; my @file= readdir DIR; closedir DIR;

This will neatly put the list of file names in the @file array (with no \n at the end of each file name).

There is a couple of other things you can improve in your code BTW:

  • use Perl style loops over arrays:
    foreach my $file (@file) { print "$file\n"; }
    this is much simpler than using C-style for( $i=0;...) loops, you don't have to use $i and $total any more (BTW $#filenames would give you the last index in the @filenames array, you don't have to use $total)
  • do not use chop but chomp instead, it's safer as it will not remove the last character of a string if it is not a newline.

Finally I have no idea why $filename$i =~ s/\*//g; is there? Is there a chance you that you might find a '*' in filenames?

Answer: How do I read all the file names of a directory into an array?
contributed by kilinrax

Use opendir, readdir and closedir.
Assuming you don't want '.' or '..' to appear in the list of filenames, the following is probably what you are looking for:

opendir DIR, "directory/"; my @files = grep { $_ ne '.' && $_ ne '..' } readdir DIR; closedir DIR;
Answer: How do I read all the file names of a directory into an array?
contributed by mrmick

You want to open the directory (handle) and read all filenames into an array using readdir. This will read all files (including . and .. into the array). From here you can use a foreach loop to iterate throught he array and do what you want:

my $directory = 'c:\windows'; opendir(DIR,$directory); my @files = readdir(DIR); closedir(DIR); foreach(@files){ print $_,"\n"; }
I hope this gets you going in the right direction...

Mick

Answer: How do I read all the file names of a directory into an array?
contributed by reyjrar

lucky for you.. perl has built in functions for this:

my $directory="/home/myuser/mp3s"; opendir(DIR, $directory) or die "couldn't open $directory: $!\n"; my @files = readdir DIR; closedir DIR;
you can also use readdir in scalar context to just return the next item in the directory.
-brad..
Answer: How do I read all the file names of a directory into an array?
contributed by gt8073a

I would like to read the names of all the files in a directory of mine into an array so that I can convert each file name into a link to that file.

very simply, use opendir, readdir, and closedir

my $dir = '/'; ## rem trailing slash my $body; ## our file list my $saveFile = '/dev/null'; ## file to save links opendir( MYDIR, $dir ) or die 'opendir'; $body = join( "\n", ## make it legible map { '<a href="$_">$_</a><br>' } ## format each file sort { $a cmp $b } ## sort them grep { ! /^\./ } ## no .name files grep { -T "$dir$_ } ## only text files readdir MYDIR ); closedir MYDIR; ## build your link page ## using $body open( FILE, $saveFile ) or die 'open'; print FILE <<EOF; <HTML> <HEAD> <TITLE>My Files</TITLE> <BODY> $body </BODY> </HTML> EOF close FILE;

see also join, grep, map, and sort
( along with Schwartzian Transform and file test operators )

--jj--

Answer: How do I read all the file names of a directory into an array?
contributed by I0

@filename=grep !/^\.\.?$/, <*>;

Answer: How do I read all the file names of a directory into an array?
contributed by epoptai

opendir DIR, "." or die "uhh: $!"; @files = readdir DIR; closedir DIR;
Answer: How do I read all the file names of a directory into an array?
contributed by feloniousMonk

You can alse use DirHandle.

Like so:

my $dhandle = new DirHandle "/directory/to/foo"; #or my $dhandle = new DirHandle "."; for #current directory, if you like if (defined($dhandle)){ while (defined($_ = $dhandle->read)){ push @filename_array,$_; } } undef($dhandle);

This is pretty much from the DirHandle manpage
also, so it's well documented. And I like it.

--
-felonious
Answer: How do I read all the file names of a directory into an array?
contributed by eg

Use backticks (`) to execute a shell command and capture its output (see the perlop manpage):

my @filename = split("\n", `ls`); my $total = scalar(@filename);

This would replace everything after the line "use strict;" and before "$error = ...".

Note you can also replace your for-loop with a foreach which would mean you wouldn't need $total any longer. See perlsyn.

Answer: How do I read all the file names of a directory into an array?
contributed by epoptai

opendir DIR, "." or die "uhh: $!"; @files = readdir DIR; closedir DIR;
Answer: How do I read all the file names of a directory into an array?
contributed by peppiv

Working off of the array of file names, this is how I created a link to the file.

#!/usr/bin/perl print "Content-type: text/html\n\n"; opendir(INFILE, "dir.dat") || die ("Unable to open directory"); #this line gets rid of . and ..<br> @files = grep !/^\./, readdir(INFILE); closedir(INFILE); foreach $file (sort @files) { print ("<font size=\"2\"face=\"arial\"><a href=/owner/$file>$ +file</a></font>\n<br>"); }

peppiv

Please (register and) log in if you wish to add an answer



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • Outside of code tags, you may need to use entities for some characters:
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.
  • Log In?
    Username:
    Password:

    What's my password?
    Create A New User
    Chatterbox?
    and the web crawler heard nothing...

    How do I use this? | Other CB clients
    Other Users?
    Others taking refuge in the Monastery: (6)
    As of 2014-11-21 03:18 GMT
    Sections?
    Information?
    Find Nodes?
    Leftovers?
      Voting Booth?

      My preferred Perl binaries come from:














      Results (104 votes), past polls