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.
[edit] Ada
with Ada.Directories; use Ada.Directories;
and then
Delete_File ("input.txt");
Delete_File ("/input.txt");
Delete_Tree ("docs");
Delete_Tree ("/docs");
Naming conventions for the file path are OS-specific. The language does not specify the encoding of the file paths, the directory separators or brackets, the file extension delimiter, the file version delimiter and syntax. The example provided works under Linux and Windows.
[edit] Aikido
The remove function removes either a file or a directory (the directory must be empty for this to work). Exception is thrown if this fails.
remove ("input.txt")
remove ("/input.txt")
remove ("docs")
remove ("/docs")
[edit] ALGOL 68
Note: scratch does not appear to do anything on ALGOL 68G. Also note that file names are Operating System dependent.
main:(
PROC remove = (STRING file name)INT:
BEGIN
FILE actual file;
INT errno = open(actual file, file name, stand back channel);
IF errno NE 0 THEN stop remove FI;
scratch(actual file); # detach the book and burn it #
errno
EXIT
stop remove:
errno
END;
remove("input.txt");
remove("/input.txt");
remove("docs");
remove("/docs")
)
[edit] AutoHotkey
FileDelete, input.txt
FileDelete, \input.txt
FileRemoveDir, docs, 1
FileRemoveDir, \docs, 1
[edit] AWK
Assuming we are on a Unix/Linux or at least Cygwin system:
system("rm input.txt");
system("rm /input.txt");
system("rm -rf docs");
system("rm -rf /docs");
[edit] Batch File
del input.txt
rd /s /q docs
del \input.txt
rd /s /q \docs
[edit] BASIC
Some versions of Qbasic may have had a builtin RMDIR command. However this is not documented in the manual, so we use the external MSDOS command in this example.
KILL "INPUT.TXT"
KILL "C:\INPUT.TXT"
SHELL "RMDIR /S /Q DIR"
SHELL "RMDIR /S /Q C:\DIR"
The ZX Spectrum microdrive had only a main directory, and filenames did not have file extensions. Here we delete the file named INPUTTXT from the first microdrive:
ERASE "m"; 1; "INPUTTXT"
[edit] BBC BASIC
If the names are known as constants at compile time:
*DELETE input.txt
*DELETE \input.txt
*RMDIR docs
*RMDIR \docs
If the names are known only at run time:
OSCLI "DELETE " + file$
OSCLI "RMDIR " + dir$
[edit] C
ISO C:
#include <stdio.h>
int main() {
remove("input.txt");
remove("/input.txt");
remove("docs");
remove("/docs");
return 0;
}
POSIX:
#include <unistd.h>
int main() {
unlink("input.txt");
unlink("/input.txt");
rmdir("docs");
rmdir("/docs");
return 0;
}
[edit] C++
#include <cstdio>
#include <direct.h>
int main() {
remove( "input.txt" );
remove( "/input.txt" );
_rmdir( "docs" );
_rmdir( "/docs" );
return 0;
}
[edit] C#
using System;
using System.IO;
namespace RosettaCode {
class Program {
static void Main() {
try {
File.Delete("input.txt");
Directory.Delete("docs");
File.Delete(@"\input.txt");
Directory.Delete(@"\docs");
} catch (Exception exception) {
Console.WriteLine(exception.Message);
}
}
}
}
[edit] Clojure
(import '(java.io File))
(.delete (File. "output.txt"))
(.delete (File. "docs"))
(.delete (new File (str (File/separator) "output.txt")))
(.delete (new File (str (File/separator) "docs")))
[edit] COBOL
To delete files or directories in COBOL we need to use an unofficial extension. These are built-in subroutines originally created as part of Micro Focus COBOL.
IDENTIFICATION DIVISION.
PROGRAM-ID. Delete-Files.
PROCEDURE DIVISION.
CALL "CBL_DELETE_FILE" USING "input.txt"
CALL "CBL_DELETE_DIR" USING "docs"
CALL "CBL_DELETE_FILE" USING "/input.txt"
CALL "CBL_DELETE_DIR" USING "/docs"
GOBACK
.
[edit] Common Lisp
(delete-file (make-pathname :name "input.txt"))
(delete-file (make-pathname :directory '(:absolute "") :name "input.txt"))
To delete directories we need an implementation specific extension. In clisp this is ext:delete-dir.
(let ((path (make-pathname :directory '(:relative "docs"))))
(ext:delete-dir path))
(let ((path (make-pathname :directory '(:absolute "docs"))))
(ext:delete-dir path))
Or you can use the portability library CL-FAD:
(let ((path (make-pathname :directory '(:relative "docs"))))
(cl-fad:delete-directory-and-files path))
[edit] D
import std.file: remove;
void main() {
remove("data.txt");
}
import tango.io.Path;
void main() {
remove("input.txt");
remove("/input.txt");
remove("docs");
remove("/docs");
}
POSIX:
import tango.stdc.posix.unistd;
void main() {
unlink("input.txt");
unlink("/input.txt");
rmdir("docs");
rmdir("/docs");
}
[edit] Delphi
procedure TMain.btnDeleteClick(Sender: TObject);
var
CurrentDirectory : String;
begin
CurrentDirectory := GetCurrentDir;
DeleteFile(CurrentDirectory + '\input.txt');
RmDir(PChar(CurrentDirectory + '\docs'));
DeleteFile('c:\input.txt');
RmDir(PChar('c:\docs'));
end;
[edit] E
<file:input.txt>.delete(null)
<file:docs>.delete(null)
<file:///input.txt>.delete(null)
<file:///docs>.delete(null)
[edit] Erlang
-module(delete).
-export([main/0]).
main() ->
% current directory
ok = file:del_dir( "docs" ),
ok = file:delete( "input.txt" ),
% root directory
ok = file:del_dir( "/docs" ),
ok = file:delete( "/input.txt" ).
[edit] F#
open System.IO
[<EntryPoint>]
let main argv =
let fileName = "input.txt"
let dirName = "docs"
for path in ["."; "/"] do
ignore (File.Delete(Path.Combine(path, fileName)))
ignore (Directory.Delete(Path.Combine(path, dirName)))
0
[edit] Factor
"docs" "/docs" [ delete-tree ] bi@
"input.txt" "/input.txt" [ delete-file ] bi@
[edit] Forth
There is no means to delete directories in ANS Forth.
s" input.txt" delete-file throw
s" /input.txt" delete-file throw
[edit] Fortran
I don't know a way of deleting directories in Fortran
OPEN (UNIT=5, FILE="input.txt", STATUS="OLD") ! Current directory
CLOSE (UNIT=5, STATUS="DELETE")
OPEN (UNIT=5, FILE="/input.txt", STATUS="OLD") ! Root directory
CLOSE (UNIT=5, STATUS="DELETE")
[edit] GAP
# Apparently GAP can only remove a file, not a directory
RemoveFile("input.txt");
# true
RemoveFile("docs");
# fail
[edit] Go
package main
import "os"
func main() {
os.Remove("input.txt")
os.Remove("/input.txt")
os.Remove("docs")
os.Remove("/docs")
// recursively removes contents:
os.RemoveAll("docs")
os.RemoveAll("/docs")
}
[edit] Haskell
import System.IO
import System.Directory
main = do
removeFile "output.txt"
removeDirectory "docs"
removeFile "/output.txt"
removeDirectory "/docs"
[edit] HicEst
SYSTEM(DIR="docs") ! create docs in current directory (if not existent), make it current
OPEN (FILE="input.txt", "NEW") ! in current directory = docs
WRITE(FIle="input.txt", DELETE=1) ! no command to DELETE a DIRECTORY in HicEst
SYSTEM(DIR="C:\docs") ! create C:\docs (if not existent), make it current
OPEN (FILE="input.txt", "NEW") ! in current directory = C:\docs
WRITE(FIle="input.txt", DELETE=1)
[edit] Io
Directory fileNamed("input.txt") remove
Directory directoryNamed("docs") remove
RootDir := Directory clone setPath("/")
RootDir fileNamed("input.txt") remove
RootDir directoryNamed("docs") remove
or
File with("input.txt") remove
Directory with("docs") remove
File with("/input.txt") remove
Directory with("/docs") remove
[edit] Icon and Unicon
Icon supports 'remove' for files.
every dir := !["./","/"] do {
remove(f := dir || "input.txt") |stop("failure for file remove ",f)
rmdir(f := dir || "docs") |stop("failure for directory remove ",f)
}
Note Icon and Unicon accept both / and \ for directory separators.
[edit] J
The J standard library comes with a set of file access utilities.
load 'files'
ferase 'input.txt'
ferase '\input.txt'
ferase 'docs'
ferase '\docs'
NB. Or all at once...
ferase 'input.txt';'/input.txt';'docs';'/docs'
The function above actually uses a foreign conjunction and defined in the files library like so:
NB. =========================================================
NB.*ferase v erases a file
NB. Returns 1 if successful, otherwise _1
ferase=: (1!:55 :: _1:) @ (fboxname &>) @ boxopen
This means that you can directly erase files and directories without loading the files library.
1!:55 <'input.txt'
1!:55 <'\input.txt'
1!:55 <'docs'
1!:55 <'\docs'
[edit] 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);
}
}
[edit] JavaScript
var fso = new ActiveXObject("Scripting.FileSystemObject");
fso.DeleteFile('input.txt');
fso.DeleteFile('c:/input.txt');
fso.DeleteFolder('docs');
fso.DeleteFolder('c:/docs');
or
var fso = new ActiveXObject("Scripting.FileSystemObject");
var f;
f = fso.GetFile('input.txt');
f.Delete();
f = fso.GetFile('c:/input.txt');
f.Delete();
f = fso.GetFolder('docs');
f.Delete();
f = fso.GetFolder('c:/docs');
f.Delete();
[edit] LabVIEW
This image is a VI Snippet, an executable image of LabVIEW code. The LabVIEW version is shown on the top-right hand corner. You can download it, then drag-and-drop it onto the LabVIEW block diagram from a file browser, and it will appear as runnable, editable code.
[edit] Liberty BASIC
' show where we are
print DefaultDir$
' in here
kill "input.txt"
result=rmdir("Docs")
' from root
kill "\input.txt"
result=rmdir("\Docs")
[edit] Locomotive Basic
|era,"input.txt"
(AMSDOS RSX command, therefore prefixed with a vertical bar. Also, there are no subdirectories in AMSDOS.)
[edit] Logo
UCB Logo has no means to delete directories.
erasefile "input.txt
erasefile "/input.txt
[edit] Lua
os.remove("input.txt")
os.remove("/input.txt")
os.remove("docs")
os.remove("/docs")
[edit] Mathematica
wd = NotebookDirectory[];
DeleteFile[wd <> "input.txt"]
DeleteFile["/" <> "input.txt"]
DeleteDirectory[wd <> "docs"]
DeleteDirectory["/" <> "docs"]
[edit] MATLAB / Octave
delete('input.txt'); % delete local file input.txt
delete('/input.txt'); % delete file /input.txt
rmdir('docs'); % remove local directory docs
rmdir('/docs'); % remove directory /docs
On Unix-Systems:
if system('rm input.txt') == 0
disp('input.txt removed')
end
if system('rm /input.txt') == 0
disp('/input.txt removed')
end
if system('rmdir docs') == 0
disp('docs removed')
end
if system('rmdir /docs') == 0
disp('/docs removed')
end
[edit] MAXScript
There's no way to delete folders in MAXScript
-- Here
deleteFile "input.txt"
-- Root
deleteFile "\input.txt"
[edit] Nimrod
import os
removeFile("input.txt")
removeFile("/input.txt")
removeDir("docs")
removeDir("/docs")
[edit] Objective-C
NSFileManager *fm = [NSFileManager defaultManager];
// Pre-OS X 10.5
[fm removeFileAtPath:@"input.txt" handler:nil];
[fm removeFileAtPath:@"/input.txt" handler:nil];
[fm removeFileAtPath:@"docs" handler:nil];
[fm removeFileAtPath:@"/docs" handler:nil];
// OS X 10.5+
[fm removeItemAtPath:@"input.txt" error:NULL];
[fm removeItemAtPath:@"/input.txt" error:NULL];
[fm removeItemAtPath:@"docs" error:NULL];
[fm removeItemAtPath:@"/docs" error:NULL];
[edit] Objeck
use IO;
bundle Default {
class FileExample {
function : Main(args : String[]) ~ Nil {
File->Delete("output.txt");
File->Delete("/output.txt");
Directory->Delete("docs");
Directory->Delete("/docs");
}
}
}
[edit] OCaml
Sys.remove "input.txt";;
Sys.remove "/input.txt";;
with the Unix library:
#load "unix.cma";;
Unix.unlink "input.txt";;
Unix.unlink "/input.txt";;
Unix.rmdir "docs";;
Unix.rmdir "/docs";;
[edit] Oz
for Dir in ["/" "./"] do
try {OS.unlink Dir#"output.txt"}
catch _ then {System.showInfo "File does not exist."} end
try {OS.rmDir Dir#"docs"}
catch _ then {System.showInfo "Directory does not exist."} end
end
[edit] PARI/GP
GP has no built-in facilities for deleting files, but can use a system call:
system("rm -rf docs");
system("rm input.txt");
system("rm -rf /docs");
system("rm /input.txt");
PARI, as usual, has access to all the standard C methods.
[edit] Pascal
See Delphi
[edit] 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';
Without Perl Modules
Current directory
perl -e 'unlink input.txt' perl -e 'rmdir docs'
Root Directory
perl -e 'unlink "/input.txt"' perl -e 'rmdir "/docs"'
[edit] Perl 6
unlink 'input.txt';
unlink '/input.txt';
rmdir 'docs';
rmdir '/docs';
[edit] PHP
<?php
unlink('input.txt');
unlink('/input.txt');
rmdir('docs');
rmdir('/docs');
?>
[edit] PicoLisp
(call 'rm "input.txt")
(call 'rmdir "docs")
(call 'rm "/input.txt")
(call 'rmdir "/docs")
[edit] Pike
int main(){
rm("input.txt");
rm("/input.txt");
rm("docs");
rm("/docs");
}
[edit] PowerShell
# possible aliases for Remove-Item: rm, del, ri
Remove-Item input.txt
Remove-Item \input.txt # file system root
Remove-Item -Recurse docs # recurse for deleting folders including content
Remove-Item -Recurse \docs
[edit] ProDOS
Because input.txt is located inside of "docs" this will delete it when it deletes "docs"
deletedirectory docs
[edit] PureBasic
DeleteFile("input.txt")
DeleteDirectory("docs","") ; needs to delete all included files
DeleteFile("/input.txt")
DeleteDirectory("/docs","*.*") ; deletes all files according to a pattern
DeleteDirectory("/docs","",#PB_FileSystem_Recursive) ; deletes all files and directories recursive
[edit] Python
import os
# current directory
os.remove("output.txt")
os.rmdir("docs")
# root directory
os.remove("/output.txt")
os.rmdir("/docs")
If you wanted to remove a directory and all its contents, recursively, you would do:
import shutil
shutil.rmtree("docs")
[edit] R
file.remove("input.txt")
file.remove("/input.txt")
# or
file.remove("input.txt", "/input.txt")
# or
unlink("input.txt"); unlink("/input.txt")
# directories needs the recursive flag
unlink("docs", recursive = TRUE)
unlink("/docs", recursive = TRUE)
The function unlink allows wildcards (* and ?)
[edit] Racket
#lang racket
;; here
(delete-file "input.txt")
(delete-directory "docs")
(delete-directory/files "docs") ; recursive deletion
;; in the root
(delete-file "/input.txt")
(delete-directory "/docs")
(delete-directory/files "/docs")
;; or in the root with relative paths
(parameterize ([current-directory "/"])
(delete-file "input.txt")
(delete-directory "docs")
(delete-directory/files "docs"))
[edit] Raven
'input.txt' delete
'/input.txt' delete
'docs' rmdir
'/docs' rmdir
[edit] REBOL
; Local.
delete %input.txt
delete-dir %docs/
; Root.
delete %/input.txt
delete-dir %/docs/
[edit] Retro
with files'
"input.txt" delete
"/input.txt" delete
[edit] Ruby
File.delete("output.txt", "/output.txt")
Dir.delete("docs")
Dir.delete("/docs")
[edit] Run BASIC
'------ delete input.txt ----------------
kill "input.txt" ' this is where we are
kill "/input.txt" ' this is the root
' ---- delete directory docs ----------
result = rmdir("Docs") ' directory where we are
result = rmdir("/Docs") ' root directory
[edit] Scheme
[1](delete-file filename)
[edit] Slate
(It will succeed deleting the directory if it is empty)
(File newNamed: 'input.txt') delete.
(File newNamed: '/input.txt') delete.
(Directory newNamed: 'docs') delete.
(Directory newNamed: '/docs') delete.
Also:
(Directory current / 'input.txt') delete.
(Directory root / 'input.txt') delete.
[edit] Smalltalk
(It will succeed deleting the directory if it is empty)
File remove: 'input.txt'.
File remove: 'docs'.
File remove: '/input.txt'.
File remove: '/docs'
[edit] Standard ML
OS.FileSys.remove "input.txt";
OS.FileSys.remove "/input.txt";
OS.FileSys.rmDir "docs";
OS.FileSys.rmDir "/docs";
[edit] Tcl
file delete input.txt /input.txt
# preserve directory if non-empty
file delete docs /docs
# delete even if non-empty
file delete -force docs /docs
[edit] Toka
needs shell
" docs" remove
" input.txt" remove
[edit] TUSCRIPT
$$ MODE TUSCRIPT
- delete file
SET status = DELETE ("input.txt")
- delete directory
SET status = DELETE ("docs",-std-)
[edit] UNIX Shell
rm -rf docs
rm input.txt
rm -rf /docs
rm /input.txt
[edit] Vedit macro language
Vedit allows using either '\' or '/' as directory separator character, it is automatically converted to the one used by the operating system.
// In current directory
File_Delete("input.txt", OK)
File_Rmdir("docs")
// In the root directory
File_Delete("/input.txt", OK)
File_Rmdir("/docs")
[edit] VBScript
Set oFSO = CreateObject( "Scripting.FileSystemObject" )
oFSO.DeleteFile "input.txt"
oFSO.DeleteFolder "docs"
oFSO.DeleteFile "\input.txt"
oFSO.DeleteFolder "\docs"
'Using Delete on file and folder objects
dim fil, fld
set fil = oFSO.GetFile( "input.txt" )
fil.Delete
set fld = oFSO.GetFolder( "docs" )
fld.Delete
set fil = oFSO.GetFile( "\input.txt" )
fil.Delete
set fld = oFSO.GetFolder( "\docs" )
fld.Delete
[edit] Visual Basic .NET
Platform: .NET
'Current Directory
IO.Directory.Delete("docs")
IO.Directory.Delete("docs", True) 'also delete files and sub-directories
IO.File.Delete("output.txt")
'Root
IO.Directory.Delete("\docs")
IO.File.Delete("\output.txt")
'Root, platform independent
IO.Directory.Delete(IO.Path.DirectorySeparatorChar & "docs")
IO.File.Delete(IO.Path.DirectorySeparatorChar & "output.txt")
[edit] X86 Assembly
;syscall numbers for readability. :]
%define sys_rmdir 40
%define sys_unlink 10
section .text
global _start
_start:
mov ebx, fn
mov eax, sys_unlink
int 0x80
test eax, eax
js _ragequit
mov ebx, dn
mov eax, sys_rmdir
int 0x80
mov ebx, rfn
mov eax, sys_unlink
int 0x80
cmp eax, 0
je _exit
_ragequit:
mov edx, err_len
mov ecx, err_msg
mov ebx, 4
mov eax ,1
int 0x80
_exit:
push 0x1
mov eax, 1
push eax
int 0x80
ret
section .data
fn db 'inutput.txt',0
rfn db '/input.txt',0
dn db 'doc',0
err_msg db "Something went wrong! :[",0xa
err_len equ $-err_msg
[edit] Yorick
Yorick does not have a built-in function to recursively delete a directory; the rmdir function only works on empty directories.
remove, "input.txt";
remove, "/input.txt";
rmdir, "docs";
rmdir, "/docs";
- Programming Tasks
- File System Operations
- Ada
- Aikido
- ALGOL 68
- AutoHotkey
- AWK
- Batch File
- BASIC
- ZX Spectrum Basic
- BBC BASIC
- C
- C++
- C sharp
- Clojure
- COBOL
- Common Lisp
- CL-FAD
- D
- Tango
- Delphi
- E
- Erlang
- F Sharp
- Factor
- Forth
- Fortran
- GAP
- Go
- Haskell
- HicEst
- Io
- Icon
- Unicon
- J
- Java
- JavaScript
- LabVIEW
- LabVIEW CWD
- Liberty BASIC
- Locomotive Basic
- Logo
- Lua
- Mathematica
- MATLAB
- Octave
- MAXScript
- Nimrod
- Objective-C
- Objeck
- OCaml
- Oz
- PARI/GP
- Pascal
- Perl
- Perl 6
- PHP
- PicoLisp
- Pike
- PowerShell
- ProDOS
- PureBasic
- Python
- R
- Racket
- Raven
- REBOL
- Retro
- Ruby
- Run BASIC
- Scheme
- Slate
- Smalltalk
- Standard ML
- Tcl
- Toka
- TUSCRIPT
- UNIX Shell
- Vedit macro language
- VBScript
- Visual Basic .NET
- X86 Assembly
- Yorick
- Befunge/Omit
- HTML/Omit
- Openscad/Omit
- TI-83 BASIC/Omit
- TI-89 BASIC/Omit