Wednesday, November 18, 2009

Automatic File Copier

I needed a solution that would automatically copy all the images from my pentax camera to an external hard drive.
So I came up with this perl script.
I only wanted it to attempt to copy the files if both external devices were attached, so it uses the line if (-d $source_dir and –d $dest_dir) to check for this.
Once the files are copied, it waits for three minutes (180 seconds) and starts looping again.



#! /usr/local/bin/perl

use strict;

use warnings;

use File::Copy;



my $source_file;

my $source_dir='f:/dcim/100pentx';

my $dest_dir='g:/';

my $source;

my $dest;

my $status=0;





################# main_loop ####################

while (1)

{

&finddir;

print "status:$status:\n";

©files if $status == 1;

sleep 10 if $status == 0;

}



sub finddir

{

if (-d $source_dir and -d $dest_dir)

{

print "Found Directories\n";

$status=1;

}

else

{

print "Could not find source or destination";

$status=0;

}

}



sub copyfiles

{

opendir (DIR, "$source_dir") or warn "Couldn't open directory, $!";

while ($source_file = readdir DIR)

{

next if $source_file!~/\w/;

print "$source_file\n";

$source = "$source_dir/$source_file";

$dest = "$dest_dir/$source_file";

copy($source, $dest) or warn "File cannot be copied.";

}

closedir DIR;

sleep 180;

}

#################################################

1 comment:

  1. So cool, have you tested it? Does it work? And what operator are you using? I also decided I have to copy all my files and images to an external hard drive after experiencing a dreadful event (my laptop died and with it all images for Cambodia..).

    Will give it a try!

    ReplyDelete