By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
438,852 Members | 2,220 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 438,852 IT Pros & Developers. It's quick & easy.

Reading Files From Directories

P: 11
I have a directory named "X" which has many sub directorys "Y","Z","W" and many files about 20 files. and these sub directories also contain some more sub directories and files extra

check the Attched screen shot .What i need is , i want to read all the files that exists in directorys , subdirectories and need to display .

i tried until 2 loops , but unable to complete the logic well.

This is my code
Expand|Select|Wrap|Line Numbers
  1. print "Enter The Directory Path";
  2. $dir = <STDIN>;
  3. chomp($dir);
  4. opendir(DIR, $dir) || die "Unable to open the directory";
  5. @contents=readdir(DIR);
  6. foreach $listitem ( @contents )
  7. {
  8.   if ( -d $listitem )
  9.   {
  10.     opendir(DIR,$listitem)
  11.     @c2=readdir(DIR);
  12.     foreach  $l2(@c2) {
  13.       if (-d $l2) {
  14.        print $l2;
  15.        print " It's a directory!\n";
  16.       }
  17.       else
  18.       {
  19.        print $l2;
  20.          print " It's a file!\n";
  21.       }
  22.     }
  23.     }
  24.     print $listitem;
  25.   print " It's a directory!\n";
  26.   }
  27.   else
  28.   {
  29.   print $listitem;
  30.     print " It's a file!\n";
  31.   }
  32. }
  33. close(DIR);
  34.  
Attached Images
File Type: jpg Directory Structre.jpg (6.3 KB, 63 views)
Dec 2 '08 #1
Share this Question
Share on Google+
2 Replies


nithinpes
Expert 100+
P: 410
The best approach is to use File::Find module which comes default with Perl installation. Using this module, you can recursively parse a directory and get all the files.
Dec 2 '08 #2

KevinADC
Expert 2.5K+
P: 4,059
You would need to write a recursive function to do what you want to do, but File::Find is the way to go here. Read the documentation carefully, and try some code. If you get stuck post back.
Dec 2 '08 #3

Post your reply

Sign in to post your reply or Sign up for a free account.