Delete a file: Difference between revisions

From Rosetta Code
Content added Content deleted
(Added Toka)
Line 29: Line 29:
[[Category:Perl]]
[[Category:Perl]]


use File::Spec::Functions qw(catfile rootdir);
sub deleteFile($) {
# here
my ($filename) = @_;
unlink 'input.txt';
return unlink($filename);
rmdir 'docs';
}
# root dir
sub deleteDir($) {
unlink catfile rootdir, 'input.txt';
my ($filename) = @_;
rmdir catfile rootdir, 'docs';
return rmdir($filename);
}
sub test($$) {
my ($type, $filename) = @_;
# Safety check:
# unlink directory is DANGEROUS and unsupported unless root and -U.
# See: http://perldoc.perl.org/functions/unlink.html
if ($type eq "file" && -d $filename) { $type = "directory"; }
#
my $b = ($type eq "file") ? deleteFile($filename) : deleteDir($filename);
print "The following " . $type . " called " . $filename .
($b ? " was deleted." : " could not be deleted.");
}
test("file", "input.txt");
test("file", $FileSeperator . "input.txt");
test("directory", "docs");
test("directory", $FileSeperator . "docs" . $FileSeperator);

# Short version
unlink("input.txt");
unlink($FileSeperator . "input.txt");
rmdir("docs");
rmdir($FileSeperator . "docs" . $FileSeperator);


==[[Toka]]==
==[[Toka]]==

Revision as of 08:42, 7 June 2007

Task
Delete a file
You are encouraged to solve this task according to the task description, using any language you may know.

In this task, the job is to delete a file called "input.txt" and delete a directory called "docs". This should be done twice: once "here", i.e. in the current working directory and once in the filesystem root.


Java

import java.util.File;
public class FileDeleteTest {
   public static boolean deleteFile(String filename) {
       boolean exists = new File(filename).delete();
       return exists;
   }
   public static void test(String type, String filename) {
       System.out.println("The following " + type + " called " + filename + 
           (deleteFile(filename) ? " was deleted." : " could not be deleted.")
       );
   }
   public static void main(String args[]) {
        test("file", "input.txt");
        test("file", File.seperator + "input.txt");
        test("directory", "docs");
        test("directory", File.seperator + "docs" + File.seperator);
   }
}

Perl

use File::Spec::Functions qw(catfile rootdir);
# here
unlink 'input.txt';
rmdir 'docs';
# root dir
unlink catfile rootdir, 'input.txt';
rmdir catfile rootdir, 'docs';

Toka

 needs shell
 " docs" remove
 " input.txt" remove