Universität Ulm, Fakultät für Mathematik und Wirtschaftswissenschaften, SAI

Lösung zu Blatt 5 --- UNIX Datenbanken II (WS 1999/2000)

6. Ein einfacher Dateizugriff

package FileHash;

use Carp;
use IO::Dir;
use IO::File;
use strict;

sub TIEHASH {
   my ($pack, $dir) = @_;
   my $db = new IO::Dir $dir;
   croak("cannot open $dir: $!") unless defined $db;
   my $self = {
      db => $db,
      dir => $dir,
   };
   return bless $self, $pack;
}

sub STORE {
   my $fh = new IO::File ">" . $_[0]->{dir} . "/" . $_[1];
   if (defined $fh) {
      print $fh $_[2];
      $fh->close;
   }
}

sub FETCH {
   my $file = $_[0]->{dir} . "/" . $_[1];
   return undef unless -f $file; # only open regular files
   my $fh = new IO::File "<$file";
   if (defined $fh) {
      my @output = (<$fh>);
      $fh->close;
      return join("", @output);
   }
   return undef;
}

sub FIRSTKEY {
   $_[0]->{db}->rewind;
   return $_[0]->{db}->read;
}

sub NEXTKEY {
   return $_[0]->{db}->read;
}

sub EXISTS {
   return -e $_[0]->{db}->{dir} . "/" . $_[1];
}

sub DELETE {
   unless ($_[1] =~ /^\.\.?$/) {
      my $file = $_[0]->{dir} . "/" . $_[1];
      -d $file ? rmdir($file) : unlink($file); # is it a directory?
   }
}

sub CLEAR {
   my $file;
   $_[0]->{db}->rewind;
   while (defined ($file = $_[0]->{db}->read)) {
      unless ($file =~ /^\.\.?$/) {
	 -d $file ? rmdir($file) : unlink($file);
      }
   }
} 

sub DESTROY {
   $_[0]->{db}->close;
}

1;

=head1 NAME

FileHash - supplys mothods to access files through hashes

=head1 SYNOPSIS

   use FileHash;
   use strict;

   my %files;
   tie(%files, 'FileHash', "./testdir/");
   foreach my $name (sort keys %files) {
      print "$name:\n$files{$name}\n\n";
   }
   $files{test} = "Blubber";
   untie %files;

=head1 DESCRIPTION

C<FileHash> provides an interface to read directories and access files
vie a tied hash. The keys of the hash are the names of the entries of
the directory, the values are the contents of these enties.

Changing the value of an entry of the hash will change the contents
of the directory entry in the same way.

=head1 SEE ALSO

L<IO:File>
L<IO:Dir>

=head1 AUTHOR

Ingo Melzer E<lt>F<melzer@mathematik.uni-ulm.de>E<gt>

=head1 COPYRIGHT

Copyright (c) 1999 SAI - University of Ulm

=cut

Universität Fakultät SAI

Ingo Melzer, 02. Dezember 1999