|
Reading Directory Entries
Part:
1
2
3
This chapter explains:
- How to open a directory and read its entries.
- How to traverse a directory tree.
- A simple text search program.
Directory Accessing Functions
1. opendir() - A function to open the specified directory and associate it
to a directory handle with the following syntax:
rc = opendir(dir_handle, expression);
where "expression" specifies the path name of the directory to be opened, and
"dir_handle" is the variable name of the new directory handle. opendir() returns
true, if operation is successful.
Directory handle has its own name space. Same name can co-exist in different name spaces.
2. readdir() - A function to access the content of the specified directory handle.
If the function is called in a scalar context, it will return the next entry.
If the function is called in an array context, it will return the rest of entries.
Examples of calling readdir() in scalar and array contexts:
$s = readdir(dir_handle);
@a = readdir(dir_handle);
3. closedir() - A function to close the directory associated with the specified
directory handle.
closedir(dir_handle);
Sample Program - opendir.pl
The following sample program, opendir.pl, opens the current directory
twice. The first time, it reads the directory one entry at a time.
The second time, it reads all entries of the directory to an array.
#- opendir.pl
#- Copyright (c) 1995 by Dr. Herong Yang
#
print "Reading one entry at a time...\n";
opendir(DIR,".");
while ($f=readdir(DIR)) {
print "$f\n";
}
closedir(DIR);
print "\n";
print "Reading all entries into an array...\n";
opendir(DIR,".");
@a = readdir(DIR);
closedir(DIR);
for (@a) {
print "$_\n";
}
exit;
Now run this program by entering the program file name directly in a command window,
and you will get the following output:
>opendir.pl
Reading one entry at a time...
.
..
hello.pl
hello.prg
opendir.pl
Reading all entries into an array...
.
..
hello.pl
hello.prg
opendir.pl
Note that:
- Like Unix system, a Windows file directory has two special entries,
"." and ".." representing current directory and parent directory.
(Continued on next part...)
Part:
1
2
3
|