|
Working with File Systems
This chapter explains:
- How to change the current directory and make a new directory.
- How to use file test operators.
- How to get statistical information of a file.
Working with the Directory Tree
A file system is a tree structure of directories with files associated directories.
Perl offers several functions
for you to work with the directory tree:
1. chdir() - A function to reset the current directory to a directory
identified by the specified path name:
rc = chdir(path_name);
2. mkdir() - A function to make a new directory defined by the specified
path name:
rc = mkdir(path_name);
3. rmdir() - A function to remove a directory defined by the specified
path name, when the directory is empty:
rc = rmdir(path_name);
4. unlink() - A function to delete a list of files:
rc = unlink(path_name_list);
File Test Operators
Perl offers a number of unary operators to return statistics of a file.
Some commonly used ones are:
- "-e path_name" returns 1, if the path name exists.
- "-z path_name" returns 1, if the path name has zero size.
- "-s path_name" returns the size of the path name.
- "-f path_name" returns 1, if the path name is a file.
- "-d path_name" returns 1, if the path name is a directory.
- "-T path_name" returns 1, if the path name is a text file.
- "-B path_name" returns 1, if the path name is a binary file.
Statistics of a File
Instead of using individual file test operators, you can use the stat() function
to return a number of statistics of a file. The following program shows you
how to use stat():
#- stat.pl
#- Copyright (c) 1995 by Dr. Herong Yang
#
($file) = @ARGV;
die "Missing file name.\n" unless $file;
($dev,$ino,$mode,$nlink,$uid,$gid,$rdev,$size,
$atime,$mtime,$ctime,$blksize,$blocks) = stat($file);
print "dev = $dev\n";
print "ino = $ino\n";
print "mode = $mode\n";
print "nlink = $nlink\n";
print "uid = $uid\n";
print "uid = $uid\n";
print "gid = $gid\n";
print "rdev = $rdev\n";
print "size = $size\n";
print "atime = $atime\n";
print "mtime = $mtime\n";
print "ctime = $ctime\n";
print "blksize = $blksize\n";
print "blocks = $blocks\n";
exit;
If you run it on a Windows system, you will get something similar to this:
>stat.pl stat.pl
dev = 3
ino = 0
mode = 33206
nlink = 1
uid = 0
uid = 0
gid = 0
rdev = 3
size = 622
atime = 1069622049
mtime = 1069621972
ctime = 1069621496
blksize =
blocks =
|