Module 6 Resource 2

You might also like

Download as ppt, pdf, or txt
Download as ppt, pdf, or txt
You are on page 1of 13

Chapter 11 – File and Directory

Manipulation
Outline
11.1 Introduction
11.2 File Tests and sysopen
11.3 Permissions
11.4 File Manipulation
11.5 Hard Links and Symbolic Links
11.6 File Globbing
11.7 Directory Handles and Manipulation
11.8 Example: Web Site Recent-Update Page

 2001 Prentice Hall, Inc. All rights reserved.


Test Meaning Test Meaning

-r Is the file readable? -w Is the file writable?


-e Does the file exist? -z File exists and has a size
of zero.
-s File exists and has a -f Is the file a plain file?
nonzero size. The size
in bytes is returned.
-d File is directory. -T Is the file a text file?
-B File is a binary file. -M Age from last time file
was modified.
-A Age from time file was -C Age since file was
last accessed. created.
-x Is the file executable?

Fig. 11.1 Some file tests.

 2001 Prentice Hall, Inc. All rights reserved.


1 #!/usr/bin/perl Outline
2 # Fig. 11.2: fig11_02.pl
3 # A program that uses file tests
4
5 use strict;
6 use warnings;
7 The filename test -e determines
8 foreach my $file ( @ARGV ) { whether a file exists.
9 print( "Checking $file: " ); File test -f file test shows whether or not
10 a file is a plain file. Calling a file “plain”
11 if ( -e $file ) { # does file exist? means that the file is not a special type of
12 print( "$file exists!\n" ); file or listing.
13
14 if ( -f $file ) { # is the file a plain file?
15 print( "The file $file is:" );
16 print( " executable" ) if ( -x $file ); # executable? File tests –x, -r and –w
17 print( " readable" ) if ( -r $file ); # readable? show whether the file is
18 print( " writable" ) if ( -w $file ); # writable? executable, readable and
19 print( "\n" ); writable,
File respectively.
tests –M and -A return
20 print( "It is ", -s $file, " bytes.\n" ); # size the number of days (or
21 my @time = timeconv( -A $file ); # accessed
fraction thereof) since the
22 print( "Last accessed at $time[0] days, ", If a file is nonempty, -s
file was last modified or last
23 "$time[1] hours, $time[2] minutes ", returns the size of the file
accessed, respectively.
24 "and $time[3] seconds.\n" ); in bytes.
25 @time = timeconv( -M $file ); # modified
26 print( "Last modified at $time[0] days, ",
27 "$time[1] hours, $time[2] minutes, ",
28 "and $time[3] seconds ago.\n" );
29 }
 2001 Prentice Hall, Inc. All rights reserved.
30 elsif ( -d $file ) { # is it a directory? Outline
31 print( "$file is a directory!\n" );
32 }
33 } File test –d shows whether the file is
34 else { directory.
35 print( "$file doesn't exist.\n" );
36 }
37
38 print( "\n" );
39 }
40
41 sub timeconv
42 {
43 my $time = shift();
44 my $days = int( $time );
45 $time = ( $time - $days ) * 24;
46 my $hours = int( $time );
47 $time = ( $time - $hours ) * 60;
48 my $minutes = int( $time );
49 $time = ( $time - $minutes ) * 60;
50 my $seconds = int( $time );
51 return ( $days, $hours, $minutes, $seconds );
52 }

 2001 Prentice Hall, Inc. All rights reserved.


Checking fig11_02.pl: fig11_02.pl exists! Outline
The file fig11_02.pl is: executable readable writable
It is 1550 bytes.
Last accessed at 0 days, 0 hours, 0 minutes and 0 seconds.
Last modified at 0 days, 0 hours, 2 minutes, and 20 seconds ago.

Checking /home/pauldeitel: /home/pauldeitel exists!


/home/pauldeitel is a directory!

Checking file.txt: file.txt exists!


The file file.txt is: readable writable
It is 51 bytes.
Last accessed at 0 days, 2 hours, 40 minutes and 16 seconds.
Last modified at 1 days, 17 hours, 39 minutes, and 28 seconds ago.

Checking fakefile.txt: fakefile.txt doesn't exist.

 2001 Prentice Hall, Inc. All rights reserved.


Flag Meaning

O_RDONLY Open for reading only.


O_WRONLY Open for writing only.
O_RDWR Open for reading or writing.
O_CREAT Create the file if it does not
exist.
O_EXCL Do not open the file if it already
exists.
O_APPEND Append to the end of the file.
O_TRUNC Truncate the file’s existing
contents.
O_NONBLOCK Non-blocking access.
Fig. 11.3 Flags for sysopen imported from Fcntl.

 2001 Prentice Hall, Inc. All rights reserved.


Permission Allows

0 The user(s) can do nothing.


1 The user(s) can execute.
2 The user(s) can write.
3 The user(s) can execute and write.
4 The user(s) can read.
5 The user(s) can read and execute.
6 The user(s) can read and write.
7 The user(s) can read, write and
execute.
Fig. 11.4 Some of Perl’s file permissions.

 2001 Prentice Hall, Inc. All rights reserved.


1 #!/usr/bin/perl Outline
2 # Fig. 11.5: fig11_05.pl
3 # Renaming a file before accidental deletion
4
5 use warnings;
Checks if the file exists.
6 use strict;
7
8 if ( -e 'file.txt' ) {
9 print( "Do you want to write over file.txt? (yes or no): " );
10 chomp( my $response = <STDIN> );
11 rename( 'file.txt', 'file.old' )
12 or die( "Error renaming : $!" )
If the user enters no, the contents
of file.txt are copied to
13 if ( $response eq 'no' );
file.old.
14 }
15
16 open( FILE, ">file.txt" ) or die( "Error opening: $!" );
17 print( FILE "A copy of file.txt is saved in file.old.\n" );
18 close( FILE ) or die( "Cannot close: $!" );

Do you want to write over file.txt? (yes or no): no

The contents of file.txt are


overwritten.

 2001 Prentice Hall, Inc. All rights reserved.


Outline
file.txt before program executes:

This is the original text from file.txt.

file.txt after program executes:

A copy of file.txt is saved in file.old.

file.old after program executes:

This is the original text from file.txt.

 2001 Prentice Hall, Inc. All rights reserved.


1 #!usr/bin/perl Outline
2 # Fig. 11.9: fig11_09.pl
3 # Deleting a file with unlink Checks if the file is a plain
4 file.
5 use strict;
6 use warnings;
7
8 print( "Input a file you want deleted: " ); Prompts the user for a file to be
9 chomp( my $file = <STDIN> ); deleted.
10
11 if ( -f $file && unlink( $file ) ) {
12 print( "The file was successfully deleted.\n" );
13 }
14 else {
15 print( "It was not deleted: $!" ); Function unlink deletes a list of files and
16 } returns the number of files successfully
deleted.
Input a file you want deleted: file.old
The file was successfully deleted.

Input a file you want deleted: doesnotexist.txt


It was not deleted: No such file or directory

 2001 Prentice Hall, Inc. All rights reserved.


1 #!perl Outline
2 # Fig. 11.10: fig11_10.pl
3 # Website update-page creator.
4
5 use strict;
6 use warnings; The program begins by declaring
7 use CGI qw( :standard ); four variables with the keyword
our, so that these values can be
8 We declare $root to hold the value
accessed by the user-defined
9 our $indent = "|" . ( "&nbsp;" x 5 ); "I:/Apache/cgi-bin/" and use
functions that follow.
10 our $root = "I:/Apache/cgi-bin/"; chdir to change the working directory
11 chdir( $root ); to this value.
12 our @colors = qw( red orange green );
13 our @fileTypes = qw( html perl dir );
14 print( header(), start_html( -title => 'Update Page' ),
15 '<font size = "+1">' );
16 print( "$root:<br/>\n" ); Start the HTML page.
17 search( "", 1 ); Call to the function search.
18 print( "</font>" ); End the HTML page.
19 print( end_html() );
20
Function is called to begins
opendirsearch
Function create by
21 sub search
a directory handle for the current
assigning the two arguments to
22 {
directory to search. and $offset. In this
$directory
23 my ( $directory, $offset ) = @_;
24 opendir( DIR, $root . $directory )
case, $directory is "", and
25 or die( "Error opening: $!" );
$offset is 1.
26
 2001 Prentice Hall, Inc. All rights reserved.
27 foreach ( readdir( DIR ) ) { Outline
28 my $file = $directory . $_;
29 printFile( 0, $file, $_, $offset ) if ( m/\.html/ );
30 printFile( 1, $file, $_, $offset ) if ( m/\.pl/ );
31
32 if ( -d $file && /[A-Za-z]/ ) { IfThe variable
theCalls
current
Calls
$file
file
function
function
is assignedthen
is printFile
a directory,
printFile
the
if the
if
33 printFile( 2, $file, $_ . '/', $offset ); we Thewant
directoryforeachin iterate
to whichstructurewe iterates
through started
that
file the
through isall
($directory) anfile
HTML
theis afile
Perl
file.program
and
concatenated file.
directory
with
34 search( $file . '/', $offset + 1 ); directory as well using recursion.
35 print( "$indent" ) for ( 2 .. $offset ); Recursive
names
the incall
currentthetocurrent
search.
value In this from
directory.
returned call
36 print( br(), "\n" ); toreaddir.
search, we provide the new
37 next; The directory
directory name is printed
name ($file) concatenated
38 } by calling
with a path printFile.
separator.
39 } Prints the $indent in a for
40 } structure based on $offset.
41
42 sub printFile If the file was modified in the last
43 { Functionseven days (andbegins
printFile by in the
thus also
44 my ( $type, $file, $name, $offset ) = @_; readinglast
in 30
its arguments
days), bothand using the
"brand " and
45 my $full = $root . $file; Thefilename
current color is
with theare
"new!" also
root determined
directory
printed based
aftertothe file.
46 print( "$indent" ) for ( 2 .. $offset ); on assign
the type
thethe
If offile
full file
pathwas ormodified
name directoryin being
of $file thetolast
47 print( "|----" ); printed.
$full. 30 days, only the word "new!" is
48 my $color = $colors[ $type ];
49 my $extension = $fileTypes[ $type ]; printed.
50 print( "<font color = \"$color\">$extension: " ); The filename is printed.
51 print( "$_</font>\n" ); Sets the font color based on the
52 print( em( strong( "brand " ) ) ) if ( -M $full < 7 ); previously set value $color
53 print( strong( "new!" ), "\n" ) if ( -M $full < 30 ); and prints the type of file to be
54 print( br(), "\n" ); printed.
55 }

 2001 Prentice Hall, Inc. All rights reserved.


Outline

 2001 Prentice Hall, Inc. All rights reserved.

You might also like