Delete a file: Difference between revisions

From Rosetta Code
Content added Content deleted
(add zig example)
m (→‎{{header|Wren}}: Changed to Wren S/H)
 
(21 intermediate revisions by 15 users not shown)
Line 8: Line 8:


=={{header|11l}}==
=={{header|11l}}==
<lang 11l>fs:remove_file(‘output.txt’)
<syntaxhighlight lang="11l">fs:remove_file(‘output.txt’)
fs:remove_dir(‘docs’)
fs:remove_dir(‘docs’)
fs:remove_file(‘/output.txt’)
fs:remove_file(‘/output.txt’)
fs:remove_dir(‘/docs’)</lang>
fs:remove_dir(‘/docs’)</syntaxhighlight>


=={{header|8th}}==
=={{header|8th}}==
<syntaxhighlight lang="forth">
<lang Forth>
"input.txt" f:rm drop
"input.txt" f:rm drop
"/input.txt" f:rm drop
"/input.txt" f:rm drop
"docs" f:rmdir drop
"docs" f:rmdir drop
"/docs" f:rmdir drop
"/docs" f:rmdir drop
</syntaxhighlight>
</lang>
The 'drop' removes the result (true or false, indicating success or failure). It is not strictly necessary to do so, but it keeps the stack clean.
The 'drop' removes the result (true or false, indicating success or failure). It is not strictly necessary to do so, but it keeps the stack clean.
=={{header|AArch64 Assembly}}==
=={{header|AArch64 Assembly}}==
{{works with|as|Raspberry Pi 3B version Buster 64 bits}}
{{works with|as|Raspberry Pi 3B version Buster 64 bits}}
<syntaxhighlight lang="aarch64 assembly">
<lang AArch64 Assembly>
/* ARM assembly AARCH64 Raspberry PI 3B */
/* ARM assembly AARCH64 Raspberry PI 3B */
/* program deleteFic64.s */
/* program deleteFic64.s */
Line 104: Line 104:
/* for this file see task include a file in language AArch64 assembly */
/* for this file see task include a file in language AArch64 assembly */
.include "../includeARM64.inc"
.include "../includeARM64.inc"
</syntaxhighlight>
</lang>
=={{header|Action!}}==
=={{header|Action!}}==
The attached result has been obtained under DOS 2.5.
The attached result has been obtained under DOS 2.5.
<lang Action!>PROC Dir(CHAR ARRAY filter)
<syntaxhighlight lang="action!">PROC Dir(CHAR ARRAY filter)
CHAR ARRAY line(255)
CHAR ARRAY line(255)
BYTE dev=[1]
BYTE dev=[1]
Line 141: Line 141:
PrintF("Dir ""%S""%E",filter)
PrintF("Dir ""%S""%E",filter)
Dir(filter)
Dir(filter)
RETURN</lang>
RETURN</syntaxhighlight>
{{out}}
{{out}}
[https://gitlab.com/amarok8bit/action-rosetta-code/-/raw/master/images/Delete_a_file.png Screenshot from Atari 8-bit computer]
[https://gitlab.com/amarok8bit/action-rosetta-code/-/raw/master/images/Delete_a_file.png Screenshot from Atari 8-bit computer]
Line 160: Line 160:


=={{header|Ada}}==
=={{header|Ada}}==
<lang ada>with Ada.Directories; use Ada.Directories;</lang>
<syntaxhighlight lang="ada">with Ada.Directories; use Ada.Directories;</syntaxhighlight>
and then
and then
<lang ada>Delete_File ("input.txt");
<syntaxhighlight lang="ada">Delete_File ("input.txt");
Delete_File ("/input.txt");
Delete_File ("/input.txt");
Delete_Tree ("docs");
Delete_Tree ("docs");
Delete_Tree ("/docs");</lang>
Delete_Tree ("/docs");</syntaxhighlight>
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]].
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]].


=={{header|Aikido}}==
=={{header|Aikido}}==
The <code>remove</code> function removes either a file or a directory (the directory must be empty for this to work). Exception is thrown if this fails.
The <code>remove</code> function removes either a file or a directory (the directory must be empty for this to work). Exception is thrown if this fails.
<lang aikido>
<syntaxhighlight lang="aikido">
remove ("input.txt")
remove ("input.txt")
remove ("/input.txt")
remove ("/input.txt")
remove ("docs")
remove ("docs")
remove ("/docs")
remove ("/docs")
</syntaxhighlight>
</lang>


=={{header|Aime}}==
=={{header|Aime}}==
<lang aime>remove("input.txt");
<syntaxhighlight lang="aime">remove("input.txt");
remove("/input.txt");
remove("/input.txt");
remove("docs");
remove("docs");
remove("/docs");</lang>
remove("/docs");</syntaxhighlight>


=={{header|ALGOL 68}}==
=={{header|ALGOL 68}}==
Note: <tt>scratch</tt> does not appear to do anything on [[ALGOL 68G]]. Also note that file names are Operating System dependent.
Note: <tt>scratch</tt> does not appear to do anything on [[ALGOL 68G]]. Also note that file names are Operating System dependent.
<lang algol68>main:(
<syntaxhighlight lang="algol68">main:(
PROC remove = (STRING file name)INT:
PROC remove = (STRING file name)INT:
BEGIN
BEGIN
Line 201: Line 201:
remove("docs");
remove("docs");
remove("/docs")
remove("/docs")
)</lang>
)</syntaxhighlight>
=={{header|ARM Assembly}}==
=={{header|ARM Assembly}}==
{{works with|as|Raspberry Pi}}
{{works with|as|Raspberry Pi}}
<syntaxhighlight lang="arm assembly">
<lang ARM Assembly>
/* ARM assembly Raspberry PI */
/* ARM assembly Raspberry PI */
/* program deleteFic.s */
/* program deleteFic.s */
Line 283: Line 283:
/***************************************************/
/***************************************************/
.include "../affichage.inc"
.include "../affichage.inc"
</syntaxhighlight>
</lang>


=={{header|Arturo}}==
=={{header|Arturo}}==
<lang rebol>file: "input.txt"
<syntaxhighlight lang="rebol">file: "input.txt"
docs: "docs"
docs: "docs"


Line 293: Line 293:


delete join.path ["/" file]
delete join.path ["/" file]
delete.directory join.path ["/" docs]</lang>
delete.directory join.path ["/" docs]</syntaxhighlight>


=={{header|AutoHotkey}}==
=={{header|AutoHotkey}}==
<lang AutoHotkey>FileDelete, input.txt
<syntaxhighlight lang="autohotkey">FileDelete, input.txt
FileDelete, \input.txt
FileDelete, \input.txt
FileRemoveDir, docs, 1
FileRemoveDir, docs, 1
FileRemoveDir, \docs, 1</lang>
FileRemoveDir, \docs, 1</syntaxhighlight>
===with DllCall===
===with DllCall===
Source: [https://github.com/jNizM/AHK_DllCall_WinAPI/ DeleteFile @github] by jNizM
Source: [https://github.com/jNizM/AHK_DllCall_WinAPI/ DeleteFile @github] by jNizM
<lang AutoHotkey>DeleteFile(lpFileName)
<syntaxhighlight lang="autohotkey">DeleteFile(lpFileName)
{
{
DllCall("Kernel32.dll\DeleteFile", "Str", lpFileName)
DllCall("Kernel32.dll\DeleteFile", "Str", lpFileName)
}
}


DeleteFile("C:\Temp\TestFile.txt")</lang>
DeleteFile("C:\Temp\TestFile.txt")</syntaxhighlight>


=={{header|AWK}}==
=={{header|AWK}}==
Assuming we are on a Unix/Linux or at least Cygwin system:
Assuming we are on a Unix/Linux or at least Cygwin system:
<lang awk>system("rm input.txt")
<syntaxhighlight lang="awk">system("rm input.txt")
system("rm /input.txt")
system("rm /input.txt")
system("rm -rf docs")
system("rm -rf docs")
system("rm -rf /docs")</lang>
system("rm -rf /docs")</syntaxhighlight>


=={{header|Axe}}==
=={{header|Axe}}==
<lang axe>DelVar "appvINPUT"</lang>
<syntaxhighlight lang="axe">DelVar "appvINPUT"</syntaxhighlight>


=={{header|BASIC}}==
=={{header|BASIC}}==
Line 326: Line 326:
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.
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.


<lang qbasic>
<syntaxhighlight lang="qbasic">
KILL "INPUT.TXT"
KILL "INPUT.TXT"
KILL "C:\INPUT.TXT"
KILL "C:\INPUT.TXT"
SHELL "RMDIR /S /Q DIR"
SHELL "RMDIR /S /Q DIR"
SHELL "RMDIR /S /Q C:\DIR"
SHELL "RMDIR /S /Q C:\DIR"
</syntaxhighlight>
</lang>


==={{header|Applesoft BASIC}}===
There are disk volumes, but no folders in DOS 3.3.
<syntaxhighlight lang="gwbasic"> 0 PRINT CHR$ (4)"DELETE INPUT.TXT"</syntaxhighlight>
==={{header|BaCon}}===
==={{header|BaCon}}===
BaCon has a <tt>DELETE</tt> instruction, that accepts <tt>FILE|DIRECTORY|RECURSIVE</tt> options.
BaCon has a <tt>DELETE</tt> instruction, that accepts <tt>FILE|DIRECTORY|RECURSIVE</tt> options.


<lang freebasic>DELETE FILE "input.txt"
<syntaxhighlight lang="freebasic">DELETE FILE "input.txt"
DELETE FILE "/input.txt"</lang>
DELETE FILE "/input.txt"</syntaxhighlight>


Errors can be caught with the <tt>CATCH GOTO label</tt> instruction (which allows <tt>RESUME</tt> from the labelled code section).
Errors can be caught with the <tt>CATCH GOTO label</tt> instruction (which allows <tt>RESUME</tt> from the labelled code section).
Line 346: Line 349:
file extensions. Here we delete the file named INPUTTXT from the first microdrive:
file extensions. Here we delete the file named INPUTTXT from the first microdrive:


<lang zxbasic>
<syntaxhighlight lang="zxbasic">
ERASE "m"; 1; "INPUTTXT"
ERASE "m"; 1; "INPUTTXT"
</syntaxhighlight>
</lang>


And for disc drive of ZX Spectrum +3:
And for disc drive of ZX Spectrum +3:


<lang zxbasic>
<syntaxhighlight lang="zxbasic">
ERASE "a:INPUTTXT"
ERASE "a:INPUTTXT"
</syntaxhighlight>
</lang>


==={{header|BBC BASIC}}===
==={{header|BBC BASIC}}===
If the names are known as constants at compile time:
If the names are known as constants at compile time:
<lang bbcbasic>
<syntaxhighlight lang="bbcbasic">
*DELETE input.txt
*DELETE input.txt
*DELETE \input.txt
*DELETE \input.txt
*RMDIR docs
*RMDIR docs
*RMDIR \docs
*RMDIR \docs
</syntaxhighlight>
</lang>
If the names are known only at run time:
If the names are known only at run time:
<lang BBC BASIC> OSCLI "DELETE " + file$
<syntaxhighlight lang="bbc basic"> OSCLI "DELETE " + file$
OSCLI "RMDIR " + dir$</lang>
OSCLI "RMDIR " + dir$</syntaxhighlight>


==={{header|IS-BASIC}}===
==={{header|IS-BASIC}}===
<lang IS-BASIC>100 WHEN EXCEPTION USE IOERROR
<syntaxhighlight lang="is-basic">100 WHEN EXCEPTION USE IOERROR
110 EXT "del input.txt"
110 EXT "del input.txt"
120 EXT "del \input.txt"
120 EXT "del \input.txt"
Line 379: Line 382:
180 PRINT "*** ";EXSTRING$(EXTYPE)
180 PRINT "*** ";EXSTRING$(EXTYPE)
190 CONTINUE
190 CONTINUE
200 END HANDLER</lang>
200 END HANDLER</syntaxhighlight>


=={{header|Batch File}}==
=={{header|Batch File}}==
<lang dos>del input.txt
<syntaxhighlight lang="dos">del input.txt
rd /s /q docs
rd /s /q docs


del \input.txt
del \input.txt
rd /s /q \docs</lang>
rd /s /q \docs</syntaxhighlight>

=={{header|Beef}}==
<syntaxhighlight lang="csharp">using System;
using System.IO;

namespace DeleteFile {
class Program {
static void Main() {
File.Delete("input.txt");
Directory.Delete("docs");
File.Delete("/input.txt");
Directory.Delete("/docs");
}
}
}</syntaxhighlight>

=={{header|BQN}}==
File operations are under the system value <code>•file</code> in BQN.

<syntaxhighlight lang="bqn">•file.Remove "input.txt"
•file.Remove "/input.txt"
•file.RemoveDir "docs"
•file.RemoveDir "/docs"</syntaxhighlight>


=={{header|C}}==
=={{header|C}}==
ISO C:
ISO C:
<lang c>#include <stdio.h>
<syntaxhighlight lang="c">#include <stdio.h>


int main() {
int main() {
Line 398: Line 424:
remove("/docs");
remove("/docs");
return 0;
return 0;
}</lang>
}</syntaxhighlight>


POSIX:
POSIX:
<lang c>#include <unistd.h>
<syntaxhighlight lang="c">#include <unistd.h>


int main() {
int main() {
Line 409: Line 435:
rmdir("/docs");
rmdir("/docs");
return 0;
return 0;
}</lang>
}</syntaxhighlight>


=={{header|C sharp|C#}}==
=={{header|C sharp|C#}}==
<lang csharp>using System;
<syntaxhighlight lang="csharp">using System;
using System.IO;
using System.IO;


Line 428: Line 454:
}
}
}
}
}</lang>
}</syntaxhighlight>


=={{header|C++}}==
=={{header|C++}}==
<lang cpp>#include <cstdio>
<syntaxhighlight lang="cpp">#include <cstdio>
#include <direct.h>
#include <direct.h>


Line 441: Line 467:


return 0;
return 0;
}</lang>
}</syntaxhighlight>


=={{header|Clojure}}==
=={{header|Clojure}}==
<lang lisp>(import '(java.io File))
<syntaxhighlight lang="lisp">(import '(java.io File))
(.delete (File. "output.txt"))
(.delete (File. "output.txt"))
(.delete (File. "docs"))
(.delete (File. "docs"))


(.delete (new File (str (File/separator) "output.txt")))
(.delete (new File (str (File/separator) "output.txt")))
(.delete (new File (str (File/separator) "docs")))</lang>
(.delete (new File (str (File/separator) "docs")))</syntaxhighlight>


=={{header|COBOL}}==
=={{header|COBOL}}==
COBOL 2023 added a dedicated <code>DELETE FILE</code> statement.
To delete files or directories in COBOL we need to use unofficial extensions. The following are built-in subroutines originally created as part of some of the COBOL products created by Micro Focus.
{{works with|Visual COBOL}}
{{works with|Visual COBOL}}
{{works with|OpenCOBOL}}
{{works with|GnuCOBOL}}
<lang cobol> IDENTIFICATION DIVISION.
<syntaxhighlight lang="cobol"> IDENTIFICATION DIVISION.
PROGRAM-ID. Delete-Files.
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
.</lang>

Alternate method of deleting files using the <code>DELETE FILE</code> statement.
{{works with|Visual COBOL}}
<lang cobol> IDENTIFICATION DIVISION.
PROGRAM-ID. Delete-Files-2.


ENVIRONMENT DIVISION.
ENVIRONMENT DIVISION.
Line 482: Line 494:
FD Local-File.
FD Local-File.
01 Local-Record PIC X.
01 Local-Record PIC X.

FD Root-File.
FD Root-File.
01 Root-Record PIC X.
01 Root-Record PIC X.
Line 489: Line 500:
DELETE FILE Local-File
DELETE FILE Local-File
DELETE FILE Root-File
DELETE FILE Root-File
GOBACK.

END PROGRAM Delete-Files.</syntaxhighlight>

However, in some implementations we need to use unofficial extensions to delete files, or if we want to delete directories. The following are built-in subroutines originally created as part of some of the COBOL products created by Micro Focus.
{{works with|Visual COBOL}}
{{works with|GnuCOBOL}}
<syntaxhighlight lang="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.


END PROGRAM Delete-Files.</syntaxhighlight>
GOBACK
.</lang>


=={{header|Common Lisp}}==
=={{header|Common Lisp}}==
<lang lisp>(delete-file (make-pathname :name "input.txt"))
<syntaxhighlight lang="lisp">(delete-file (make-pathname :name "input.txt"))
(delete-file (make-pathname :directory '(:absolute "") :name "input.txt"))</lang>
(delete-file (make-pathname :directory '(:absolute "") :name "input.txt"))</syntaxhighlight>
To delete directories we need an implementation specific extension. In clisp this is ''ext:delete-dir''.
To delete directories we need an implementation specific extension. In clisp this is ''ext:delete-dir''.
{{works with|CLISP}}
{{works with|CLISP}}
<lang lisp>(let ((path (make-pathname :directory '(:relative "docs"))))
<syntaxhighlight lang="lisp">(let ((path (make-pathname :directory '(:relative "docs"))))
(ext:delete-dir path))
(ext:delete-dir path))


(let ((path (make-pathname :directory '(:absolute "docs"))))
(let ((path (make-pathname :directory '(:absolute "docs"))))
(ext:delete-dir path))</lang>
(ext:delete-dir path))</syntaxhighlight>


Or you can use the portability library CL-FAD:
Or you can use the portability library CL-FAD:


{{libheader|CL-FAD}}
{{libheader|CL-FAD}}
<lang lisp>(let ((path (make-pathname :directory '(:relative "docs"))))
<syntaxhighlight lang="lisp">(let ((path (make-pathname :directory '(:relative "docs"))))
(cl-fad:delete-directory-and-files path))</lang>
(cl-fad:delete-directory-and-files path))</syntaxhighlight>


=={{header|Component Pascal}}==
=={{header|Component Pascal}}==
{{Works with|BlackBox Component Builder}}
{{Works with|BlackBox Component Builder}}
<lang oberon2>
<syntaxhighlight lang="oberon2">
VAR
VAR
l: Files.Locator;
l: Files.Locator;
Line 521: Line 548:
Files.dir.Delete(l,"xx.txt");
Files.dir.Delete(l,"xx.txt");
END ...
END ...
</syntaxhighlight>
</lang>


=={{header|D}}==
=={{header|D}}==
{{works with|D|2}}
{{works with|D|2}}
<lang d>import std.file: remove;
<syntaxhighlight lang="d">import std.file: remove;


void main() {
void main() {
remove("data.txt");
remove("data.txt");
}</lang>
}</syntaxhighlight>
{{libheader|Tango}}
{{libheader|Tango}}
<lang d>import tango.io.Path;
<syntaxhighlight lang="d">import tango.io.Path;


void main() {
void main() {
Line 538: Line 565:
remove("docs");
remove("docs");
remove("/docs");
remove("/docs");
}</lang>
}</syntaxhighlight>


{{libheader|Tango}}
{{libheader|Tango}}
POSIX:
POSIX:
<lang d>import tango.stdc.posix.unistd;
<syntaxhighlight lang="d">import tango.stdc.posix.unistd;


void main() {
void main() {
Line 549: Line 576:
rmdir("docs");
rmdir("docs");
rmdir("/docs");
rmdir("/docs");
}</lang>
}</syntaxhighlight>


=={{header|Delphi}}==
=={{header|Delphi}}==
<lang e>procedure TMain.btnDeleteClick(Sender: TObject);
<syntaxhighlight lang="e">procedure TMain.btnDeleteClick(Sender: TObject);
var
var
CurrentDirectory : String;
CurrentDirectory : String;
Line 564: Line 591:
RmDir(PChar('c:\docs'));
RmDir(PChar('c:\docs'));
end;
end;
</syntaxhighlight>
</lang>


=={{header|E}}==
=={{header|E}}==
<lang e><file:input.txt>.delete(null)
<syntaxhighlight lang="e"><file:input.txt>.delete(null)
<file:docs>.delete(null)
<file:docs>.delete(null)
<file:///input.txt>.delete(null)
<file:///input.txt>.delete(null)
<file:///docs>.delete(null)</lang>
<file:///docs>.delete(null)</syntaxhighlight>


=={{header|Elena}}==
=={{header|Elena}}==
ELENA 4.x :
ELENA 4.x :
<lang elena>import system'io;
<syntaxhighlight lang="elena">import system'io;
public program()
public program()
Line 585: Line 612:
Directory.assign("\docs").delete();
Directory.assign("\docs").delete();
}</lang>
}</syntaxhighlight>


=={{header|Elixir}}==
=={{header|Elixir}}==
<lang elixir>File.rm!("input.txt")
<syntaxhighlight lang="elixir">File.rm!("input.txt")
File.rmdir!("docs")
File.rmdir!("docs")
File.rm!("/input.txt")
File.rm!("/input.txt")
File.rmdir!("/docs")</lang>
File.rmdir!("/docs")</syntaxhighlight>


=={{header|Emacs Lisp}}==
=={{header|Emacs Lisp}}==
<syntaxhighlight lang="lisp">(delete-file "input.txt")
<lang Lisp>
(delete-directory "docs")
;; function to remove file & directory
(delete-file "/input.txt")
(defun my-files-rm ()
(delete-file "input.txt")
(delete-directory "/docs")</syntaxhighlight>
(delete-directory "docs"))

(my-files-rm)
(cd "~/") ;; change to home dir
(my-files-rm)
</lang>


=={{header|Erlang}}==
=={{header|Erlang}}==
<lang erlang>
<syntaxhighlight lang="erlang">
-module(delete).
-module(delete).
-export([main/0]).
-export([main/0]).
Line 617: Line 638:
ok = file:del_dir( "/docs" ),
ok = file:del_dir( "/docs" ),
ok = file:delete( "/input.txt" ).
ok = file:delete( "/input.txt" ).
</syntaxhighlight>
</lang>


=={{header|F_Sharp|F#}}==
=={{header|F_Sharp|F#}}==
<lang fsharp>open System.IO
<syntaxhighlight lang="fsharp">open System.IO


[<EntryPoint>]
[<EntryPoint>]
Line 629: Line 650:
ignore (File.Delete(Path.Combine(path, fileName)))
ignore (File.Delete(Path.Combine(path, fileName)))
ignore (Directory.Delete(Path.Combine(path, dirName)))
ignore (Directory.Delete(Path.Combine(path, dirName)))
0</lang>
0</syntaxhighlight>


=={{header|Factor}}==
=={{header|Factor}}==
<lang factor>"docs" "/docs" [ delete-tree ] bi@
<syntaxhighlight lang="factor">"docs" "/docs" [ delete-tree ] bi@
"input.txt" "/input.txt" [ delete-file ] bi@</lang>
"input.txt" "/input.txt" [ delete-file ] bi@</syntaxhighlight>


=={{header|Forth}}==
=={{header|Forth}}==
There is no means to delete directories in ANS Forth.
There is no means to delete directories in ANS Forth.
<lang forth> s" input.txt" delete-file throw
<syntaxhighlight lang="forth"> s" input.txt" delete-file throw
s" /input.txt" delete-file throw</lang>
s" /input.txt" delete-file throw</syntaxhighlight>


=={{header|Fortran}}==
=={{header|Fortran}}==
Line 644: Line 665:
{{works with|Fortran|90 and later}}
{{works with|Fortran|90 and later}}


<lang fortran> OPEN (UNIT=5, FILE="input.txt", STATUS="OLD") ! Current directory
<syntaxhighlight lang="fortran"> OPEN (UNIT=5, FILE="input.txt", STATUS="OLD") ! Current directory
CLOSE (UNIT=5, STATUS="DELETE")
CLOSE (UNIT=5, STATUS="DELETE")
OPEN (UNIT=5, FILE="/input.txt", STATUS="OLD") ! Root directory
OPEN (UNIT=5, FILE="/input.txt", STATUS="OLD") ! Root directory
CLOSE (UNIT=5, STATUS="DELETE")</lang>
CLOSE (UNIT=5, STATUS="DELETE")</syntaxhighlight>
=== Intel Fortran on Windows ===
=== Intel Fortran on Windows ===


Use Intel Fortran bindings to the Win32 API. Here we are using the [https://docs.microsoft.com/en-us/windows/win32/api/fileapi/nf-fileapi-deletefilea DeleteFileA] and [https://docs.microsoft.com/en-us/windows/win32/api/fileapi/nf-fileapi-removedirectorya RemoveDirectoryA] functions.
Use Intel Fortran bindings to the Win32 API. Here we are using the [https://docs.microsoft.com/en-us/windows/win32/api/fileapi/nf-fileapi-deletefilea DeleteFileA] and [https://docs.microsoft.com/en-us/windows/win32/api/fileapi/nf-fileapi-removedirectorya RemoveDirectoryA] functions.


<lang fortran>program DeleteFileExample
<syntaxhighlight lang="fortran">program DeleteFileExample
use kernel32
use kernel32
implicit none
implicit none
Line 659: Line 680:
print *, RemoveDirectory("docs")
print *, RemoveDirectory("docs")
print *, RemoveDirectory("\docs")
print *, RemoveDirectory("\docs")
end program</lang>
end program</syntaxhighlight>


=={{header|Free Pascal}}==
=={{header|Free Pascal}}==
All required functions already exist in the RTL’s (run-time library) <code>system</code> unit which is shipped with every FPC (Free Pascal compiler) distribution and automatically included by every program.
All required functions already exist in the RTL’s (run-time library) <code>system</code> unit which is shipped with every FPC (Free Pascal compiler) distribution and automatically included by every program.
<lang pascal>program deletion(input, output, stdErr);
<syntaxhighlight lang="pascal">program deletion(input, output, stdErr);
const
const
rootDirectory = '/'; // might have to be altered for other platforms
rootDirectory = '/'; // might have to be altered for other platforms
Line 680: Line 701:
rmDir(rootDirectory + docsFilename);
rmDir(rootDirectory + docsFilename);
end.</lang>
end.</syntaxhighlight>
Note, depending on the <code>{$IOChecks}</code> compiler switch state, run-time error generation is inserted.
Note, depending on the <code>{$IOChecks}</code> compiler switch state, run-time error generation is inserted.
In particular deletion of non-existent files or lack of privileges may cause an abort.
In particular deletion of non-existent files or lack of privileges may cause an abort.
Line 688: Line 709:


=={{header|FreeBASIC}}==
=={{header|FreeBASIC}}==
<lang freebasic>' FB 1.05.0 Win64
<syntaxhighlight lang="freebasic">' FB 1.05.0 Win64
' delete file and empty sub-directory in current directory
' delete file and empty sub-directory in current directory
Line 703: Line 724:
Print "Press any key to quit"
Print "Press any key to quit"
Sleep
Sleep
</syntaxhighlight>
</lang>


=={{header|Furor}}==
=={{header|Furor}}==
<syntaxhighlight lang="furor">
<lang Furor>
###sysinclude dir.uh
###sysinclude dir.uh
// ===================
// ===================
Line 713: Line 734:
2 argv removefile
2 argv removefile
end
end
</syntaxhighlight>
</lang>
<pre>
<pre>
Usage: furor removefile.upu filename
Usage: furor removefile.upu filename
</pre>
</pre>


<syntaxhighlight lang="furor">
<lang Furor>
###sysinclude dir.uh
###sysinclude dir.uh
#g argc 3 < { ."Usage: " #s 0 argv print SPACE 1 argv print SPACE ."unnecessary_directory\n" end }
#g argc 3 < { ."Usage: " #s 0 argv print SPACE 1 argv print SPACE ."unnecessary_directory\n" end }
Line 725: Line 746:
}
}
end
end
</syntaxhighlight>
</lang>
<pre>
<pre>
Usage: furor rmdir.upu unnecessary_directory
Usage: furor rmdir.upu unnecessary_directory
Line 731: Line 752:




=={{header|Peri}}==
<syntaxhighlight lang="peri">
###sysinclude standard.uh
###sysinclude args.uh
###sysinclude str.uh
###sysinclude io.uh
// ===================
#g argc 3 < { #s ."Usage: " 0 argv print SPACE 1 argv print ." filename\n" end }
2 argv 'e inv istrue { #s ."The given file ( " 2 argv print ." ) doesn't exist!\n" end }
2 argv removefile
end
</syntaxhighlight>
<pre>
Usage: peri removefile.upu filename
</pre>

<syntaxhighlight lang="peri">
###sysinclude standard.uh
###sysinclude args.uh
###sysinclude str.uh
###sysinclude io.uh
#g argc 3 < { ."Usage: " #s 0 argv print SPACE 1 argv print SPACE ."unnecessary_directory\n" end }
2 argv 'd inv istrue { ."The given directory doesn't exist! Exited.\n" }{
2 argv rmdir
}
end
</syntaxhighlight>
<pre>
Usage: peri rmdir.upu unnecessary_directory
</pre>

=={{header|FutureBasic}}==
<syntaxhighlight lang="futurebasic">
include "NSLog.incl"

CFURLRef url

url = fn URLFileURLWithPath( fn StringByExpandingTildeInPath( @"~/Desktop/input.txt" ) )
if (fn FileManagerRemoveItemAtURL( url ) )
NSLog( @"File \"intput.txt\" deleted." )
else
NSLog( @"Unable to delete file \"input.txt\"." )
end if

url = fn URLFileURLWithPath( fn StringByExpandingTildeInPath( @"~/Desktop/docs" ) )
if (fn FileManagerRemoveItemAtURL( url ) )
NSLog( @"Directory \"docs\" deleted." )
else
NSLog( @"Unabled to delete directory \"docs\"." )
end if

HandleEvents
</syntaxhighlight>


=={{header|Gambas}}==
=={{header|Gambas}}==
<lang gambas>Public Sub Main()
<syntaxhighlight lang="gambas">Public Sub Main()


Kill User.home &/ "input.txt"
Kill User.home &/ "input.txt"
Line 740: Line 814:
'Administrative privileges (sudo) would be required to mess about in Root - I'm not going there!
'Administrative privileges (sudo) would be required to mess about in Root - I'm not going there!


End</lang>
End</syntaxhighlight>


=={{header|GAP}}==
=={{header|GAP}}==
<lang gap># Apparently GAP can only remove a file, not a directory
<syntaxhighlight lang="gap"># Apparently GAP can only remove a file, not a directory
RemoveFile("input.txt");
RemoveFile("input.txt");
# true
# true
RemoveFile("docs");
RemoveFile("docs");
# fail</lang>
# fail</syntaxhighlight>


=={{header|Go}}==
=={{header|Go}}==
<lang go>package main
<syntaxhighlight lang="go">package main
import "os"
import "os"


Line 761: Line 835:
os.RemoveAll("docs")
os.RemoveAll("docs")
os.RemoveAll("/docs")
os.RemoveAll("/docs")
}</lang>
}</syntaxhighlight>


=={{header|Groovy}}==
=={{header|Groovy}}==
On most *nix systems, this must be run as sudo for the files in root to be deleted. If you don't have permissions, it will silently fail to delete those files. I would recommend against running anything you find on the internet as sudo.
On most *nix systems, this must be run as sudo for the files in root to be deleted. If you don't have permissions, it will silently fail to delete those files. I would recommend against running anything you find on the internet as sudo.


<lang groovy>// Gets the first filesystem root. On most systems this will be / or c:\
<syntaxhighlight lang="groovy">// Gets the first filesystem root. On most systems this will be / or c:\
def fsRoot = File.listRoots().first()
def fsRoot = File.listRoots().first()


Line 783: Line 857:
files.each{
files.each{
it.directory ? it.deleteDir() : it.delete()
it.directory ? it.deleteDir() : it.delete()
}</lang>
}</syntaxhighlight>


=={{header|Haskell}}==
=={{header|Haskell}}==


<lang haskell>import System.IO
<syntaxhighlight lang="haskell">import System.IO
import System.Directory
import System.Directory


Line 794: Line 868:
removeDirectory "docs"
removeDirectory "docs"
removeFile "/output.txt"
removeFile "/output.txt"
removeDirectory "/docs"</lang>
removeDirectory "/docs"</syntaxhighlight>


=={{header|HicEst}}==
=={{header|HicEst}}==
<lang hicest>SYSTEM(DIR="docs") ! create docs in current directory (if not existent), make it current
<syntaxhighlight lang="hicest">SYSTEM(DIR="docs") ! create docs in current directory (if not existent), make it current
OPEN (FILE="input.txt", "NEW") ! in current directory = docs
OPEN (FILE="input.txt", "NEW") ! in current directory = docs
WRITE(FIle="input.txt", DELETE=1) ! no command to DELETE a DIRECTORY in HicEst
WRITE(FIle="input.txt", DELETE=1) ! no command to DELETE a DIRECTORY in HicEst
Line 803: Line 877:
SYSTEM(DIR="C:\docs") ! create C:\docs (if not existent), make it current
SYSTEM(DIR="C:\docs") ! create C:\docs (if not existent), make it current
OPEN (FILE="input.txt", "NEW") ! in current directory = C:\docs
OPEN (FILE="input.txt", "NEW") ! in current directory = C:\docs
WRITE(FIle="input.txt", DELETE=1)</lang>
WRITE(FIle="input.txt", DELETE=1)</syntaxhighlight>


=={{header|Icon}} and {{header|Unicon}}==
=={{header|Icon}} and {{header|Unicon}}==
Icon supports 'remove' for files.
Icon supports 'remove' for files.
<lang Unicon>every dir := !["./","/"] do {
<syntaxhighlight lang="unicon">every dir := !["./","/"] do {
remove(f := dir || "input.txt") |stop("failure for file remove ",f)
remove(f := dir || "input.txt") |stop("failure for file remove ",f)
rmdir(f := dir || "docs") |stop("failure for directory remove ",f)
rmdir(f := dir || "docs") |stop("failure for directory remove ",f)
}
}
</syntaxhighlight>
</lang>
Note Icon and Unicon accept both / and \ for directory separators.
Note Icon and Unicon accept both / and \ for directory separators.


=={{header|Io}}==
=={{header|Io}}==
<lang io>Directory fileNamed("input.txt") remove
<syntaxhighlight lang="io">Directory fileNamed("input.txt") remove
Directory directoryNamed("docs") remove
Directory directoryNamed("docs") remove
RootDir := Directory clone setPath("/")
RootDir := Directory clone setPath("/")
RootDir fileNamed("input.txt") remove
RootDir fileNamed("input.txt") remove
RootDir directoryNamed("docs") remove</lang>
RootDir directoryNamed("docs") remove</syntaxhighlight>


or
or
<lang io>File with("input.txt") remove
<syntaxhighlight lang="io">File with("input.txt") remove
Directory with("docs") remove
Directory with("docs") remove
File with("/input.txt") remove
File with("/input.txt") remove
Directory with("/docs") remove</lang>
Directory with("/docs") remove</syntaxhighlight>


=={{header|J}}==
=={{header|J}}==
The J standard library comes with a set of file access utilities.
The J standard library comes with a set of file access utilities.
<lang j> load 'files'
<syntaxhighlight lang="j"> load 'files'
ferase 'input.txt'
ferase 'input.txt'
ferase '\input.txt'
ferase '\input.txt'
Line 836: Line 910:


NB. Or all at once...
NB. Or all at once...
ferase 'input.txt';'/input.txt';'docs';'/docs'</lang>
ferase 'input.txt';'/input.txt';'docs';'/docs'</syntaxhighlight>


The function above actually uses a foreign conjunction and defined in the <tt>files</tt> library like so:
The function above actually uses a foreign conjunction and defined in the <tt>files</tt> library like so:
<lang j>NB. =========================================================
<syntaxhighlight lang="j">NB. =========================================================
NB.*ferase v erases a file
NB.*ferase v erases a file
NB. Returns 1 if successful, otherwise _1
NB. Returns 1 if successful, otherwise _1
ferase=: (1!:55 :: _1:) @ (fboxname &>) @ boxopen</lang>
ferase=: (1!:55 :: _1:) @ (fboxname &>) @ boxopen</syntaxhighlight>


This means that you can directly erase files and directories without loading the <tt>files</tt> library.
This means that you can directly erase files and directories without loading the <tt>files</tt> library.
<lang j>1!:55 <'input.txt'
<syntaxhighlight lang="j">1!:55 <'input.txt'
1!:55 <'\input.txt'
1!:55 <'\input.txt'
1!:55 <'docs'
1!:55 <'docs'
1!:55 <'\docs'</lang>
1!:55 <'\docs'</syntaxhighlight>


=={{header|Java}}==
=={{header|Java}}==


<lang java>import java.io.File;
<syntaxhighlight lang="java">import java.io.File;


public class FileDeleteTest {
public class FileDeleteTest {
Line 872: Line 946:
test("directory", File.seperator + "docs" + File.seperator);
test("directory", File.seperator + "docs" + File.seperator);
}
}
}</lang>
}</syntaxhighlight>


=={{header|JavaScript}}==
=={{header|JavaScript}}==
{{works with|JScript}}
{{works with|JScript}}
<lang javascript>var fso = new ActiveXObject("Scripting.FileSystemObject");
<syntaxhighlight lang="javascript">var fso = new ActiveXObject("Scripting.FileSystemObject");


fso.DeleteFile('input.txt');
fso.DeleteFile('input.txt');
Line 882: Line 956:


fso.DeleteFolder('docs');
fso.DeleteFolder('docs');
fso.DeleteFolder('c:/docs');</lang>
fso.DeleteFolder('c:/docs');</syntaxhighlight>


or
or


<lang javascript>var fso = new ActiveXObject("Scripting.FileSystemObject");
<syntaxhighlight lang="javascript">var fso = new ActiveXObject("Scripting.FileSystemObject");
var f;
var f;
f = fso.GetFile('input.txt');
f = fso.GetFile('input.txt');
Line 895: Line 969:
f.Delete();
f.Delete();
f = fso.GetFolder('c:/docs');
f = fso.GetFolder('c:/docs');
f.Delete();</lang>
f.Delete();</syntaxhighlight>


{{works with|Node.js}}
{{works with|Node.js}}
Synchronous
Synchronous
<lang javascript>const fs = require('fs');
<syntaxhighlight lang="javascript">const fs = require('fs');
fs.unlinkSync('myfile.txt');</lang>
fs.unlinkSync('myfile.txt');</syntaxhighlight>
Asynchronous
Asynchronous
<lang javascript>const fs = require('fs');
<syntaxhighlight lang="javascript">const fs = require('fs');
fs.unlink('myfile.txt', ()=>{
fs.unlink('myfile.txt', ()=>{
console.log("Done!");
console.log("Done!");
})</lang>
})</syntaxhighlight>

=={{header|Joy}}==
<syntaxhighlight lang="joy">"input.txt" fremove
"docs" fremove
"/input.txt" fremove
"/docs" fremove.</syntaxhighlight>


=={{header|Julia}}==
=={{header|Julia}}==
<lang julia>
<syntaxhighlight lang="julia">
# Delete a file
# Delete a file
rm("input.txt")
rm("input.txt")
Line 914: Line 994:
# Delete a directory
# Delete a directory
rm("docs", recursive = true)
rm("docs", recursive = true)
</syntaxhighlight>
</lang>


=={{header|Kotlin}}==
=={{header|Kotlin}}==
<lang scala>// version 1.0.6
<syntaxhighlight lang="scala">// version 1.0.6


/* testing on Windows 10 which needs administrative privileges
/* testing on Windows 10 which needs administrative privileges
Line 934: Line 1,014:
println("$path could not be deleted")
println("$path could not be deleted")
}
}
}</lang>
}</syntaxhighlight>


{{out}}
{{out}}
Line 955: Line 1,035:
{{libheader|LabVIEW_CWD}}
{{libheader|LabVIEW_CWD}}
{{VI solution|LabVIEW_Delete_a_file.png}}
{{VI solution|LabVIEW_Delete_a_file.png}}

=={{header|Lang}}==
{{libheader|lang-io-module}}
<syntaxhighlight lang="lang">
# Load the IO module
# Replace "<pathToIO.lm>" with the location where the io.lm Lang module was installed to without "<" and ">"
ln.loadModule(<pathToIO.lm>)

$file1 = [[io]]::fp.openFile(input.txt)
[[io]]::fp.delete($file1)
[[io]]::fp.closeFile($file1)

$file2 = [[io]]::fp.openFile(/input.txt)
[[io]]::fp.delete($file2)
[[io]]::fp.closeFile($file2)

$dir1 = [[io]]::fp.openFile(docs)
[[io]]::fp.delete($dir1)
[[io]]::fp.closeFile($dir1)

$dir2 = [[io]]::fp.openFile(/docs)
[[io]]::fp.delete($dir2)
[[io]]::fp.closeFile($dir2)
</syntaxhighlight>


=={{header|Lasso}}==
=={{header|Lasso}}==
<lang Lasso>// delete file
<syntaxhighlight lang="lasso">// delete file
local(f = file('input.txt'))
local(f = file('input.txt'))
#f->delete
#f->delete
Line 973: Line 1,077:
// directory must be empty before it can be successfully deleted. A failure is generated if the operation fails.
// directory must be empty before it can be successfully deleted. A failure is generated if the operation fails.
local(d = file('//docs'))
local(d = file('//docs'))
#d->delete</lang>
#d->delete</syntaxhighlight>


=={{header|Liberty BASIC}}==
=={{header|Liberty BASIC}}==
<lang lb>' show where we are
<syntaxhighlight lang="lb">' show where we are
print DefaultDir$
print DefaultDir$


Line 986: Line 1,090:
kill "\input.txt"
kill "\input.txt"
result=rmdir("\Docs")
result=rmdir("\Docs")
</syntaxhighlight>
</lang>


=={{header|Lingo}}==
=={{header|Lingo}}==


Delete file "input.txt" in cwd:
Delete file "input.txt" in cwd:
<lang lingo>-- note: fileIO xtra is shipped with Director, i.e. an "internal"
<syntaxhighlight lang="lingo">-- note: fileIO xtra is shipped with Director, i.e. an "internal"
fp = xtra("fileIO").new()
fp = xtra("fileIO").new()
fp.openFile("input.txt", 0)
fp.openFile("input.txt", 0)
fp.delete()</lang>
fp.delete()</syntaxhighlight>


Delete file "input.txt" in root of current volume:
Delete file "input.txt" in root of current volume:
<lang lingo>-- note: fileIO xtra is shipped with Director, i.e. an "internal"
<syntaxhighlight lang="lingo">-- note: fileIO xtra is shipped with Director, i.e. an "internal"
pd = the last char of _movie.path -- "\" for win, ":" for mac
pd = the last char of _movie.path -- "\" for win, ":" for mac
_player.itemDelimiter = pd
_player.itemDelimiter = pd
Line 1,003: Line 1,107:
fp = xtra("fileIO").new()
fp = xtra("fileIO").new()
fp.openFile(vol&pd&"input.txt", 0)
fp.openFile(vol&pd&"input.txt", 0)
fp.delete()</lang>
fp.delete()</syntaxhighlight>


Deleting a directory requires a 3rd party xtra, but there are various free xtras that allow this. Here as example usage of BinFile xtra:
Deleting a directory requires a 3rd party xtra, but there are various free xtras that allow this. Here as example usage of BinFile xtra:


<lang lingo>-- delete (empty) directory "docs" in cwd
<syntaxhighlight lang="lingo">-- delete (empty) directory "docs" in cwd
bx_folder_delete("docs")
bx_folder_delete("docs")


Line 1,014: Line 1,118:
_player.itemDelimiter = pd
_player.itemDelimiter = pd
vol = _movie.path.item[1]
vol = _movie.path.item[1]
bx_folder_delete(vol&pd&"docs")</lang>
bx_folder_delete(vol&pd&"docs")</syntaxhighlight>


=={{header|Locomotive Basic}}==
=={{header|Locomotive Basic}}==


<lang locobasic>|era,"input.txt"</lang>
<syntaxhighlight lang="locobasic">|era,"input.txt"</syntaxhighlight>
([[wp:AMSDOS|AMSDOS]] RSX command, therefore prefixed with a vertical bar. Also, there are no subdirectories in AMSDOS.)
([[wp:AMSDOS|AMSDOS]] RSX command, therefore prefixed with a vertical bar. Also, there are no subdirectories in AMSDOS.)


Line 1,024: Line 1,128:
{{works with|UCB Logo}}
{{works with|UCB Logo}}
UCB Logo has no means to delete directories.
UCB Logo has no means to delete directories.
<lang logo>erasefile "input.txt
<syntaxhighlight lang="logo">erasefile "input.txt
erasefile "/input.txt</lang>
erasefile "/input.txt</syntaxhighlight>


=={{header|Lua}}==
=={{header|Lua}}==
<lang lua>os.remove("input.txt")
<syntaxhighlight lang="lua">os.remove("input.txt")
os.remove("/input.txt")
os.remove("/input.txt")
os.remove("docs")
os.remove("docs")
os.remove("/docs")</lang>
os.remove("/docs")</syntaxhighlight>


=={{header|Maple}}==
=={{header|Maple}}==
<lang Maple>FileTools:-Remove("input.txt");
<syntaxhighlight lang="maple">FileTools:-Remove("input.txt");
FileTools:-RemoveDirectory("docs");
FileTools:-RemoveDirectory("docs");
FileTools:-Remove("/input.txt");
FileTools:-Remove("/input.txt");
FileTools:-RemoveDirectory("/docs");
FileTools:-RemoveDirectory("/docs");
</syntaxhighlight>
</lang>


=={{header|Mathematica}} / {{header|Wolfram Language}}==
=={{header|Mathematica}} / {{header|Wolfram Language}}==
<lang Mathematica>wd = NotebookDirectory[];
<syntaxhighlight lang="mathematica">wd = NotebookDirectory[];
DeleteFile[wd <> "input.txt"]
DeleteFile[wd <> "input.txt"]
DeleteFile["/" <> "input.txt"]
DeleteFile["/" <> "input.txt"]
DeleteDirectory[wd <> "docs"]
DeleteDirectory[wd <> "docs"]
DeleteDirectory["/" <> "docs"]</lang>
DeleteDirectory["/" <> "docs"]</syntaxhighlight>


=={{header|MATLAB}} / {{header|Octave}}==
=={{header|MATLAB}} / {{header|Octave}}==


<lang Matlab> delete('input.txt'); % delete local file input.txt
<syntaxhighlight lang="matlab"> delete('input.txt'); % delete local file input.txt
delete('/input.txt'); % delete file /input.txt
delete('/input.txt'); % delete file /input.txt
rmdir('docs'); % remove local directory docs
rmdir('docs'); % remove local directory docs
rmdir('/docs'); % remove directory /docs
rmdir('/docs'); % remove directory /docs
</lang>
</syntaxhighlight>


On Unix-Systems:
On Unix-Systems:
<lang matlab>if system('rm input.txt') == 0
<syntaxhighlight lang="matlab">if system('rm input.txt') == 0
disp('input.txt removed')
disp('input.txt removed')
end
end
Line 1,067: Line 1,171:
if system('rmdir /docs') == 0
if system('rmdir /docs') == 0
disp('/docs removed')
disp('/docs removed')
end</lang>
end</syntaxhighlight>


=={{header|MAXScript}}==
=={{header|MAXScript}}==
There's no way to delete folders in MAXScript
There's no way to delete folders in MAXScript
<lang maxscript>-- Here
<syntaxhighlight lang="maxscript">-- Here
deleteFile "input.txt"
deleteFile "input.txt"
-- Root
-- Root
deleteFile "\input.txt"</lang>
deleteFile "\input.txt"</syntaxhighlight>


=={{header|Mercury}}==
=={{header|Mercury}}==
<lang mercury>:- module delete_file.
<syntaxhighlight lang="mercury">:- module delete_file.
:- interface.
:- interface.


Line 1,090: Line 1,194:
io.remove_file("/input.txt", _, !IO),
io.remove_file("/input.txt", _, !IO),
io.remove_file("docs", _, !IO),
io.remove_file("docs", _, !IO),
io.remove_file("/docs", _, !IO).</lang>
io.remove_file("/docs", _, !IO).</syntaxhighlight>


=={{header|Nanoquery}}==
=={{header|Nanoquery}}==
{{trans|Ursa}}
{{trans|Ursa}}
<lang Nanoquery>f = new(Nanoquery.IO.File)
<syntaxhighlight lang="nanoquery">f = new(Nanoquery.IO.File)
f.delete("input.txt")
f.delete("input.txt")
f.delete("docs")
f.delete("docs")
f.delete("/input.txt")
f.delete("/input.txt")
f.delete("/docs")</lang>
f.delete("/docs")</syntaxhighlight>


=={{header|Nemerle}}==
=={{header|Nemerle}}==
<lang Nemerle>using System;
<syntaxhighlight lang="nemerle">using System;
using System.IO;
using System.IO;
using System.Console;
using System.Console;
Line 1,120: Line 1,224:
when (Directory.Exists(@"\docs")) Directory.Delete(@"\docs");
when (Directory.Exists(@"\docs")) Directory.Delete(@"\docs");
}
}
}</lang>
}</syntaxhighlight>


=={{header|NetRexx}}==
=={{header|NetRexx}}==
<lang NetRexx>/* NetRexx */
<syntaxhighlight lang="netrexx">/* NetRexx */
options replace format comments java crossref symbols binary
options replace format comments java crossref symbols binary


Line 1,158: Line 1,262:


return
return
</syntaxhighlight>
</lang>


=={{header|NewLISP}}==
=={{header|NewLISP}}==
<lang NewLISP>(delete-file "input.txt")
<syntaxhighlight lang="newlisp">(delete-file "input.txt")
(delete-file "/input.txt")
(delete-file "/input.txt")
(remove-dir "docs")
(remove-dir "docs")
(remove-dir "/docs")</lang>
(remove-dir "/docs")</syntaxhighlight>


=={{header|Nim}}==
=={{header|Nim}}==
<lang Nim>import os
<syntaxhighlight lang="nim">import os
removeFile("input.txt")
removeFile("input.txt")
removeFile("/input.txt")
removeFile("/input.txt")
removeDir("docs")
removeDir("docs")
removeDir("/docs")</lang>
removeDir("/docs")</syntaxhighlight>


=={{header|Objeck}}==
=={{header|Objeck}}==
<lang objeck>
<syntaxhighlight lang="objeck">
use IO;
use IO;


Line 1,188: Line 1,292:
}
}
}
}
</syntaxhighlight>
</lang>


=={{header|Objective-C}}==
=={{header|Objective-C}}==


<lang objc>NSFileManager *fm = [NSFileManager defaultManager];
<syntaxhighlight lang="objc">NSFileManager *fm = [NSFileManager defaultManager];


// Pre-OS X 10.5
// Pre-OS X 10.5
Line 1,204: Line 1,308:
[fm removeItemAtPath:@"/input.txt" error:NULL];
[fm removeItemAtPath:@"/input.txt" error:NULL];
[fm removeItemAtPath:@"docs" error:NULL];
[fm removeItemAtPath:@"docs" error:NULL];
[fm removeItemAtPath:@"/docs" error:NULL];</lang>
[fm removeItemAtPath:@"/docs" error:NULL];</syntaxhighlight>


=={{header|OCaml}}==
=={{header|OCaml}}==


<lang ocaml>Sys.remove "input.txt";;
<syntaxhighlight lang="ocaml">Sys.remove "input.txt";;
Sys.remove "/input.txt";;</lang>
Sys.remove "/input.txt";;
Sys.rmdir "docs";;
Sys.rmdir "/docs";;</syntaxhighlight>


with the Unix library:
with the Unix library:
<lang ocaml>#load "unix.cma";;
<syntaxhighlight lang="ocaml">#load "unix.cma";;
Unix.unlink "input.txt";;
Unix.unlink "input.txt";;
Unix.unlink "/input.txt";;
Unix.unlink "/input.txt";;
Unix.rmdir "docs";;
Unix.rmdir "docs";;
Unix.rmdir "/docs";;</lang>
Unix.rmdir "/docs";;</syntaxhighlight>


=={{header|ooRexx}}==
=={{header|ooRexx}}==
<lang oorexx>/*REXX pgm deletes a file */
<syntaxhighlight lang="oorexx">/*REXX pgm deletes a file */
file= 'afile.txt' /*name of a file to be deleted.*/
file= 'afile.txt' /*name of a file to be deleted.*/
res=sysFileDelete(file); Say file 'res='res
res=sysFileDelete(file); Say file 'res='res
File= 'bfile.txt' /*name of a file to be deleted.*/
File= 'bfile.txt' /*name of a file to be deleted.*/
res=sysFileDelete(file); Say file 'res='res</lang>
res=sysFileDelete(file); Say file 'res='res</syntaxhighlight>
{{out}}
{{out}}
<pre>afile.txt res=0
<pre>afile.txt res=0
Line 1,229: Line 1,335:


=={{header|Oz}}==
=={{header|Oz}}==
<lang oz>for Dir in ["/" "./"] do
<syntaxhighlight lang="oz">for Dir in ["/" "./"] do
try {OS.unlink Dir#"output.txt"}
try {OS.unlink Dir#"output.txt"}
catch _ then {System.showInfo "File does not exist."} end
catch _ then {System.showInfo "File does not exist."} end
try {OS.rmDir Dir#"docs"}
try {OS.rmDir Dir#"docs"}
catch _ then {System.showInfo "Directory does not exist."} end
catch _ then {System.showInfo "Directory does not exist."} end
end</lang>
end</syntaxhighlight>


=={{header|PARI/GP}}==
=={{header|PARI/GP}}==
GP has no built-in facilities for deleting files, but can use a system call:
GP has no built-in facilities for deleting files, but can use a system call:
<lang parigp>system("rm -rf docs");
<syntaxhighlight lang="parigp">system("rm -rf docs");
system("rm input.txt");
system("rm input.txt");
system("rm -rf /docs");
system("rm -rf /docs");
system("rm /input.txt");</lang>
system("rm /input.txt");</syntaxhighlight>
PARI, as usual, has access to all the standard [[#C|C]] methods.
PARI, as usual, has access to all the standard [[#C|C]] methods.


Line 1,249: Line 1,355:
=={{header|Perl}}==
=={{header|Perl}}==


<lang perl>use File::Spec::Functions qw(catfile rootdir);
<syntaxhighlight lang="perl">use File::Spec::Functions qw(catfile rootdir);
# here
# here
unlink 'input.txt';
unlink 'input.txt';
Line 1,255: Line 1,361:
# root dir
# root dir
unlink catfile rootdir, 'input.txt';
unlink catfile rootdir, 'input.txt';
rmdir catfile rootdir, 'docs';</lang>
rmdir catfile rootdir, 'docs';</syntaxhighlight>


'''Without Perl Modules'''
'''Without Perl Modules'''
Line 1,268: Line 1,374:


=={{header|Phix}}==
=={{header|Phix}}==
<!--<syntaxhighlight lang="phix">(notonline)-->
<lang Phix>constant root = iff(platform()=LINUX?"/":"C:\\")
<span style="color: #008080;">without</span> <span style="color: #008080;">js</span> <span style="color: #000080;font-style:italic;">-- (file i/o)</span>
?delete_file("input.txt")
<span style="color: #008080;">constant</span> <span style="color: #000000;">root</span> <span style="color: #0000FF;">=</span> <span style="color: #008080;">iff</span><span style="color: #0000FF;">(</span><span style="color: #7060A8;">platform</span><span style="color: #0000FF;">()=</span><span style="color: #004600;">LINUX</span><span style="color: #0000FF;">?</span><span style="color: #008000;">"/"</span><span style="color: #0000FF;">:</span><span style="color: #008000;">"C:\\"</span><span style="color: #0000FF;">)</span>
?delete_file(root&"input.txt")
<span style="color: #0000FF;">?</span><span style="color: #7060A8;">delete_file</span><span style="color: #0000FF;">(</span><span style="color: #008000;">"input.txt"</span><span style="color: #0000FF;">)</span>
?remove_directory("docs")
<span style="color: #0000FF;">?</span><span style="color: #7060A8;">delete_file</span><span style="color: #0000FF;">(</span><span style="color: #000000;">root</span><span style="color: #0000FF;">&</span><span style="color: #008000;">"input.txt"</span><span style="color: #0000FF;">)</span>
?remove_directory(root&"docs")</lang>
<span style="color: #0000FF;">?</span><span style="color: #000000;">remove_directory</span><span style="color: #0000FF;">(</span><span style="color: #008000;">"docs"</span><span style="color: #0000FF;">)</span>
<span style="color: #0000FF;">?</span><span style="color: #000000;">remove_directory</span><span style="color: #0000FF;">(</span><span style="color: #000000;">root</span><span style="color: #0000FF;">&</span><span style="color: #008000;">"docs"</span><span style="color: #0000FF;">)</span>
<!--</syntaxhighlight>-->
output is 0 0 0 0 or 1 1 1 1 or some combination thereof
output is 0 0 0 0 or 1 1 1 1 or some combination thereof


=={{header|PHP}}==
=={{header|PHP}}==
<lang php><?php
<syntaxhighlight lang="php"><?php
unlink('input.txt');
unlink('input.txt');
unlink('/input.txt');
unlink('/input.txt');
rmdir('docs');
rmdir('docs');
rmdir('/docs');
rmdir('/docs');
?></lang>
?></syntaxhighlight>

=={{header|Picat}}==
{{works with|Picat}}
<syntaxhighlight lang="picat">
import os.

del(Arg), directory(Arg) =>
rmdir(Arg).

del(Arg), file(Arg) =>
rm(Arg).

main(Args) =>
foreach (Arg in Args)
del(Arg)
end.
</syntaxhighlight>
{{out}}
<pre>
picat delete_file.pi input.txt docs/ /input.txt /docs/
</pre>


=={{header|PicoLisp}}==
=={{header|PicoLisp}}==
<lang PicoLisp>(call 'rm "input.txt")
<syntaxhighlight lang="picolisp">(call 'rm "input.txt")
(call 'rmdir "docs")
(call 'rmdir "docs")
(call 'rm "/input.txt")
(call 'rm "/input.txt")
(call 'rmdir "/docs")</lang>
(call 'rmdir "/docs")</syntaxhighlight>


=={{header|Pike}}==
=={{header|Pike}}==
<lang pike>int main(){
<syntaxhighlight lang="pike">int main(){
rm("input.txt");
rm("input.txt");
rm("/input.txt");
rm("/input.txt");
rm("docs");
rm("docs");
rm("/docs");
rm("/docs");
}</lang>
}</syntaxhighlight>

=={{header|Plain English}}==
<syntaxhighlight lang="text">
To run:
Start up.
\ In the current working directory
Destroy ".\input.txt" in the file system.
Destroy ".\docs\" in the file system.
\ In the filesystem root
Destroy "C:\input.txt" in the file system.
Destroy "C:\docs\" in the file system.
Shut down.
</syntaxhighlight>


=={{header|PowerShell}}==
=={{header|PowerShell}}==
<lang powershell># possible aliases for Remove-Item: rm, del, ri
<syntaxhighlight lang="powershell"># possible aliases for Remove-Item: rm, del, ri
Remove-Item input.txt
Remove-Item input.txt
Remove-Item \input.txt # file system root
Remove-Item \input.txt # file system root


Remove-Item -Recurse docs # recurse for deleting folders including content
Remove-Item -Recurse docs # recurse for deleting folders including content
Remove-Item -Recurse \docs</lang>
Remove-Item -Recurse \docs</syntaxhighlight>


=={{header|ProDOS}}==
=={{header|ProDOS}}==
Because input.txt is located inside of "docs" this will delete it when it deletes "docs"
Because input.txt is located inside of "docs" this will delete it when it deletes "docs"
<lang ProDOS>deletedirectory docs</lang>
<syntaxhighlight lang="prodos">deletedirectory docs</syntaxhighlight>


=={{header|PureBasic}}==
=={{header|PureBasic}}==
<lang PureBasic>DeleteFile("input.txt")
<syntaxhighlight lang="purebasic">DeleteFile("input.txt")
DeleteDirectory("docs","") ; needs to delete all included files
DeleteDirectory("docs","") ; needs to delete all included files
DeleteFile("/input.txt")
DeleteFile("/input.txt")
DeleteDirectory("/docs","*.*") ; deletes all files according to a pattern
DeleteDirectory("/docs","*.*") ; deletes all files according to a pattern


DeleteDirectory("/docs","",#PB_FileSystem_Recursive) ; deletes all files and directories recursive</lang>
DeleteDirectory("/docs","",#PB_FileSystem_Recursive) ; deletes all files and directories recursive</syntaxhighlight>


=={{header|Python}}==
=={{header|Python}}==


<lang python>import os
<syntaxhighlight lang="python">import os
# current directory
# current directory
os.remove("output.txt")
os.remove("output.txt")
Line 1,325: Line 1,468:
# root directory
# root directory
os.remove("/output.txt")
os.remove("/output.txt")
os.rmdir("/docs")</lang>
os.rmdir("/docs")</syntaxhighlight>
If you wanted to remove a directory and all its contents, recursively, you would do:
If you wanted to remove a directory and all its contents, recursively, you would do:
<lang python>import shutil
<syntaxhighlight lang="python">import shutil
shutil.rmtree("docs")</lang>
shutil.rmtree("docs")</syntaxhighlight>


=={{header|R}}==
=={{header|R}}==
<lang R>file.remove("input.txt")
<syntaxhighlight lang="r">file.remove("input.txt")
file.remove("/input.txt")
file.remove("/input.txt")


Line 1,342: Line 1,485:
# directories needs the recursive flag
# directories needs the recursive flag
unlink("docs", recursive = TRUE)
unlink("docs", recursive = TRUE)
unlink("/docs", recursive = TRUE)</lang>
unlink("/docs", recursive = TRUE)</syntaxhighlight>


The function <tt>unlink</tt> allows wildcards (* and ?)
The function <tt>unlink</tt> allows wildcards (* and ?)
Line 1,348: Line 1,491:
=={{header|Racket}}==
=={{header|Racket}}==


<syntaxhighlight lang="racket">
<lang Racket>
#lang racket
#lang racket


Line 1,366: Line 1,509:
(delete-directory "docs")
(delete-directory "docs")
(delete-directory/files "docs"))
(delete-directory/files "docs"))
</syntaxhighlight>
</lang>


=={{header|Raku}}==
=={{header|Raku}}==
(formerly Perl 6)
(formerly Perl 6)
<lang perl6>unlink 'input.txt';
<syntaxhighlight lang="raku" line>unlink 'input.txt';
unlink '/input.txt';
unlink '/input.txt';
rmdir 'docs';
rmdir 'docs';
rmdir '/docs';</lang>
rmdir '/docs';</syntaxhighlight>


=={{header|Raven}}==
=={{header|Raven}}==


<lang raven>'input.txt' delete
<syntaxhighlight lang="raven">'input.txt' delete
'/input.txt' delete
'/input.txt' delete
'docs' rmdir
'docs' rmdir
'/docs' rmdir</lang>
'/docs' rmdir</syntaxhighlight>


=={{header|REBOL}}==
=={{header|REBOL}}==
<lang REBOL>; Local.
<syntaxhighlight lang="rebol">; Local.
delete %input.txt
delete %input.txt
delete-dir %docs/
delete-dir %docs/
Line 1,389: Line 1,532:
; Root.
; Root.
delete %/input.txt
delete %/input.txt
delete-dir %/docs/</lang>
delete-dir %/docs/</syntaxhighlight>


=={{header|Retro}}==
=={{header|Retro}}==
<lang Retro>'input.txt file:delete
<syntaxhighlight lang="retro">'input.txt file:delete
'/input.txt file:delete</lang>
'/input.txt file:delete</syntaxhighlight>


=={{header|REXX}}==
=={{header|REXX}}==
Note that this REXX program will work on the Next family of Microsoft Windows systems as well as DOS &nbsp; (both under Windows in a DOS-prompt window or stand-alone DOS).
Note that this REXX program will work on the Next family of Microsoft Windows systems as well as DOS &nbsp; (both under Windows in a DOS-prompt window or stand-alone DOS).
<lang rexx>/*REXX program deletes a file and a folder in the current directory and the root. */
<syntaxhighlight lang="rexx">/*REXX program deletes a file and a folder in the current directory and the root. */
trace off /*suppress REXX error messages from DOS*/
trace off /*suppress REXX error messages from DOS*/
aFile= 'input.txt' /*name of a file to be deleted. */
aFile= 'input.txt' /*name of a file to be deleted. */
Line 1,406: Line 1,549:
if j==1 then 'CD \' /*make the current dir the root dir.*/
if j==1 then 'CD \' /*make the current dir the root dir.*/
end /* [↑] just do CD \ command once.*/
end /* [↑] just do CD \ command once.*/
/*stick a fork in it, we're all done. */</lang>
/*stick a fork in it, we're all done. */</syntaxhighlight>


=={{header|Ring}}==
=={{header|Ring}}==


<lang ring>
<syntaxhighlight lang="ring">
remove("output.txt")
remove("output.txt")
system("rmdir docs")
system("rmdir docs")
</syntaxhighlight>
</lang>

=={{header|RPL}}==
There is a unique RPL instruction to delete both files and directories. Directories must be empty to be deletable.
'output.txt' PURGE
'docs' PURGE
HOME output.txt' PURGE
HOME 'docs' PURGE
Basically, <code>HOME</code> moves the user from the current directory to the root. If the last two commands are done successively, only the first call is necessary.


=={{header|Ruby}}==
=={{header|Ruby}}==


<lang ruby>File.delete("output.txt", "/output.txt")
<syntaxhighlight lang="ruby">File.delete("output.txt", "/output.txt")
Dir.delete("docs")
Dir.delete("docs")
Dir.delete("/docs")</lang>
Dir.delete("/docs")</syntaxhighlight>


=={{header|Run BASIC}}==
=={{header|Run BASIC}}==
<lang runbasic>'------ delete input.txt ----------------
<syntaxhighlight lang="runbasic">'------ delete input.txt ----------------
kill "input.txt" ' this is where we are
kill "input.txt" ' this is where we are
kill "/input.txt" ' this is the root
kill "/input.txt" ' this is the root
Line 1,428: Line 1,579:
' ---- delete directory docs ----------
' ---- delete directory docs ----------
result = rmdir("Docs") ' directory where we are
result = rmdir("Docs") ' directory where we are
result = rmdir("/Docs") ' root directory</lang>
result = rmdir("/Docs") ' root directory</syntaxhighlight>


=={{header|Rust}}==
=={{header|Rust}}==
<lang rust>use std::io::{self, Write};
<syntaxhighlight lang="rust">use std::io::{self, Write};
use std::fs::{remove_file,remove_dir};
use std::fs::{remove_file,remove_dir};
use std::path::Path;
use std::path::Path;
Line 1,455: Line 1,606:
let _ = writeln!(&mut io::stderr(), "{:?}", error);
let _ = writeln!(&mut io::stderr(), "{:?}", error);
process::exit(code)
process::exit(code)
}</lang>
}</syntaxhighlight>


=={{header|Scala}}==
=={{header|Scala}}==
{{libheader|Scala}}
{{libheader|Scala}}
<lang scala>import java.util._
<syntaxhighlight lang="scala">import java.util._
import java.io.File
import java.io.File


Line 1,473: Line 1,624:
test("directory", "docs")
test("directory", "docs")
test("directory", File.separatorChar + "docs" + File.separatorChar)
test("directory", File.separatorChar + "docs" + File.separatorChar)
}</lang>
}</syntaxhighlight>


=={{header|Scheme}}==
=={{header|Scheme}}==
{{works with|Scheme|R6RS}}[http://www.r6rs.org/final/html/r6rs-lib/r6rs-lib-Z-H-10.html]
{{works with|Scheme|R6RS}}[http://www.r6rs.org/final/html/r6rs-lib/r6rs-lib-Z-H-10.html]
<lang scheme>(delete-file filename)</lang>
<syntaxhighlight lang="scheme">(delete-file filename)</syntaxhighlight>


=={{header|Seed7}}==
=={{header|Seed7}}==
The library [http://seed7.sourceforge.net/libraries/osfiles.htm osfiles.s7i] provides the functions [http://seed7.sourceforge.net/libraries/osfiles.htm#removeFile%28in_string%29 removeFile] and [http://seed7.sourceforge.net/libraries/osfiles.htm#removeTree%28in_string%29 removeTree]. RemoveFile removes a file of any type unless it is a directory that is not empty. RemoveTree remove a file of any type inclusive a directory tree. Note that removeFile and removeTree fail with the exception [http://seed7.sourceforge.net/manual/errors.htm#FILE_ERROR FILE_ERROR] when the file does not exist.
The library [http://seed7.sourceforge.net/libraries/osfiles.htm osfiles.s7i] provides the functions [http://seed7.sourceforge.net/libraries/osfiles.htm#removeFile%28in_string%29 removeFile] and [http://seed7.sourceforge.net/libraries/osfiles.htm#removeTree%28in_string%29 removeTree]. RemoveFile removes a file of any type unless it is a directory that is not empty. RemoveTree remove a file of any type inclusive a directory tree. Note that removeFile and removeTree fail with the exception [http://seed7.sourceforge.net/manual/errors.htm#FILE_ERROR FILE_ERROR] when the file does not exist.
<lang seed7>$ include "seed7_05.s7i";
<syntaxhighlight lang="seed7">$ include "seed7_05.s7i";
include "osfiles.s7i";
include "osfiles.s7i";


Line 1,490: Line 1,641:
removeTree("docs");
removeTree("docs");
removeTree("/docs");
removeTree("/docs");
end func;</lang>
end func;</syntaxhighlight>


=={{header|SenseTalk}}==
=={{header|SenseTalk}}==
<lang sensetalk>// Delete locally (relative to "the folder")
<syntaxhighlight lang="sensetalk">// Delete locally (relative to "the folder")
delete file "input.txt"
delete file "input.txt"
delete folder "docs"
delete folder "docs"
Line 1,500: Line 1,651:
delete file "/input.txt"
delete file "/input.txt"
delete folder "/docs"
delete folder "/docs"
</syntaxhighlight>
</lang>


=={{header|Sidef}}==
=={{header|Sidef}}==
<lang ruby># here
<syntaxhighlight lang="ruby"># here
%f'input.txt' -> delete;
%f'input.txt' -> delete;
%d'docs' -> delete;
%d'docs' -> delete;
Line 1,509: Line 1,660:
# root dir
# root dir
Dir.root + %f'input.txt' -> delete;
Dir.root + %f'input.txt' -> delete;
Dir.root + %d'docs' -> delete;</lang>
Dir.root + %d'docs' -> delete;</syntaxhighlight>


=={{header|Slate}}==
=={{header|Slate}}==
Line 1,515: Line 1,666:
(It will succeed deleting the directory if it is empty)
(It will succeed deleting the directory if it is empty)


<lang slate>(File newNamed: 'input.txt') delete.
<syntaxhighlight lang="slate">(File newNamed: 'input.txt') delete.
(File newNamed: '/input.txt') delete.
(File newNamed: '/input.txt') delete.
(Directory newNamed: 'docs') delete.
(Directory newNamed: 'docs') delete.
(Directory newNamed: '/docs') delete.</lang>
(Directory newNamed: '/docs') delete.</syntaxhighlight>


Also:
Also:


<lang slate>
<syntaxhighlight lang="slate">
(Directory current / 'input.txt') delete.
(Directory current / 'input.txt') delete.
(Directory root / 'input.txt') delete.</lang>
(Directory root / 'input.txt') delete.</syntaxhighlight>


=={{header|Smalltalk}}==
=={{header|Smalltalk}}==
Line 1,530: Line 1,681:
(It will succeed deleting the directory if it is empty)
(It will succeed deleting the directory if it is empty)


<lang smalltalk>File remove: 'input.txt'.
<syntaxhighlight lang="smalltalk">File remove: 'input.txt'.
File remove: 'docs'.
File remove: 'docs'.
File remove: '/input.txt'.
File remove: '/input.txt'.
File remove: '/docs'</lang>
File remove: '/docs'</syntaxhighlight>


=={{header|Standard ML}}==
=={{header|Standard ML}}==


<lang sml>OS.FileSys.remove "input.txt";
<syntaxhighlight lang="sml">OS.FileSys.remove "input.txt";
OS.FileSys.remove "/input.txt";
OS.FileSys.remove "/input.txt";
OS.FileSys.rmDir "docs";
OS.FileSys.rmDir "docs";
OS.FileSys.rmDir "/docs";</lang>
OS.FileSys.rmDir "/docs";</syntaxhighlight>


=={{header|Stata}}==
=={{header|Stata}}==
<lang stata>erase input.txt
<syntaxhighlight lang="stata">erase input.txt
rmdir docs</lang>
rmdir docs</syntaxhighlight>


=={{header|Tcl}}==
=={{header|Tcl}}==


<lang tcl>file delete input.txt /input.txt
<syntaxhighlight lang="tcl">file delete input.txt /input.txt


# preserve directory if non-empty
# preserve directory if non-empty
Line 1,554: Line 1,705:


# delete even if non-empty
# delete even if non-empty
file delete -force docs /docs</lang>
file delete -force docs /docs</syntaxhighlight>


=={{header|Toka}}==
=={{header|Toka}}==


<lang toka>needs shell
<syntaxhighlight lang="toka">needs shell
" docs" remove
" docs" remove
" input.txt" remove</lang>
" input.txt" remove</syntaxhighlight>


=={{header|TUSCRIPT}}==
=={{header|TUSCRIPT}}==
<lang tuscript>
<syntaxhighlight lang="tuscript">
$$ MODE TUSCRIPT
$$ MODE TUSCRIPT
- delete file
- delete file
Line 1,569: Line 1,720:
- delete directory
- delete directory
SET status = DELETE ("docs",-std-)
SET status = DELETE ("docs",-std-)
</syntaxhighlight>
</lang>


=={{header|UNIX Shell}}==
=={{header|UNIX Shell}}==
<lang bash>rm -rf docs
<syntaxhighlight lang="bash">rm -rf docs
rm input.txt
rm input.txt
rm -rf /docs
rm -rf /docs
rm /input.txt</lang>
rm /input.txt</syntaxhighlight>


=={{header|Ursa}}==
=={{header|Ursa}}==
<lang ursa>decl file f
<syntaxhighlight lang="ursa">decl file f
f.delete "input.txt"
f.delete "input.txt"
f.delete "docs"
f.delete "docs"
f.delete "/input.txt"
f.delete "/input.txt"
f.delete "/docs"</lang>
f.delete "/docs"</syntaxhighlight>


=={{header|VAX Assembly}}==
=={{header|VAX Assembly}}==
<lang VAX Assembly>74 75 70 6E 69 20 65 74 65 6C 65 64 0000 1 dcl: .ascii "delete input.txt;,docs.dir;"
<syntaxhighlight lang="vax assembly">74 75 70 6E 69 20 65 74 65 6C 65 64 0000 1 dcl: .ascii "delete input.txt;,docs.dir;"
64 2E 73 63 6F 64 2C 3B 74 78 74 2E 000C
64 2E 73 63 6F 64 2C 3B 74 78 74 2E 000C
3B 72 69 0018
3B 72 69 0018
Line 1,604: Line 1,755:
0071 12 .end main
0071 12 .end main


</syntaxhighlight>
</lang>


=={{header|VBA}}==
=={{header|VBA}}==
<lang vb>Option Explicit
<syntaxhighlight lang="vb">Option Explicit


Sub DeleteFileOrDirectory()
Sub DeleteFileOrDirectory()
Line 1,616: Line 1,767:
'delete Directory
'delete Directory
RmDir myPath
RmDir myPath
End Sub</lang>
End Sub</syntaxhighlight>


=={{header|VBScript}}==
=={{header|VBScript}}==
<lang vb>Set oFSO = CreateObject( "Scripting.FileSystemObject" )
<syntaxhighlight lang="vb">Set oFSO = CreateObject( "Scripting.FileSystemObject" )


oFSO.DeleteFile "input.txt"
oFSO.DeleteFile "input.txt"
Line 1,641: Line 1,792:
fld.Delete
fld.Delete


</syntaxhighlight>
</lang>


=={{header|Vedit macro language}}==
=={{header|Vedit macro language}}==
Vedit allows using either '\' or '/' as directory separator character, it is automatically converted to the one used by the operating system.
Vedit allows using either '\' or '/' as directory separator character, it is automatically converted to the one used by the operating system.
<lang vedit>// In current directory
<syntaxhighlight lang="vedit">// In current directory
File_Delete("input.txt", OK)
File_Delete("input.txt", OK)
File_Rmdir("docs")
File_Rmdir("docs")
Line 1,651: Line 1,802:
// In the root directory
// In the root directory
File_Delete("/input.txt", OK)
File_Delete("/input.txt", OK)
File_Rmdir("/docs")</lang>
File_Rmdir("/docs")</syntaxhighlight>


=={{header|Visual Basic .NET}}==
=={{header|Visual Basic .NET}}==
Line 1,657: Line 1,808:


{{works with|Visual Basic .NET|9.0+}}
{{works with|Visual Basic .NET|9.0+}}
<lang vbnet>'Current Directory
<syntaxhighlight lang="vbnet">'Current Directory
IO.Directory.Delete("docs")
IO.Directory.Delete("docs")
IO.Directory.Delete("docs", True) 'also delete files and sub-directories
IO.Directory.Delete("docs", True) 'also delete files and sub-directories
Line 1,668: Line 1,819:
'Root, platform independent
'Root, platform independent
IO.Directory.Delete(IO.Path.DirectorySeparatorChar & "docs")
IO.Directory.Delete(IO.Path.DirectorySeparatorChar & "docs")
IO.File.Delete(IO.Path.DirectorySeparatorChar & "output.txt")</lang>
IO.File.Delete(IO.Path.DirectorySeparatorChar & "output.txt")</syntaxhighlight>

=={{header|V (Vlang)}}==
<syntaxhighlight lang="Rust">
import os

fn main() {
os.rm("./input.txt") or {println(err) exit(-1)}
os.rmdir("./docs") or {println(err) exit(-2)} // os.rmdir_all, recursively removes specified directory
// check if file exists
if os.is_file("./input.txt") == true {println("Found file!")}
else {println("File was not found!")}
// check if directory exists
if os.is_dir("./docs") == true {println("Found directory!")}
else {println("Directory was not found!")}
}
</syntaxhighlight>


=={{header|Wren}}==
=={{header|Wren}}==
Line 1,674: Line 1,841:


Wren does not currently support the removal of directories.
Wren does not currently support the removal of directories.
<lang ecmascript>import "io" for File
<syntaxhighlight lang="wren">import "io" for File


File.delete("input.txt")
File.delete("input.txt")


// check it worked
// check it worked
System.print(File.exists("input.txt"))</lang>
System.print(File.exists("input.txt"))</syntaxhighlight>


{{out}}
{{out}}
Line 1,689: Line 1,856:
{{works with|NASM|Linux}}
{{works with|NASM|Linux}}


<lang asm>
<syntaxhighlight lang="asm">
;syscall numbers for readability. :]
;syscall numbers for readability. :]
%define sys_rmdir 40
%define sys_rmdir 40
Line 1,735: Line 1,902:
err_msg db "Something went wrong! :[",0xa
err_msg db "Something went wrong! :[",0xa
err_len equ $-err_msg
err_len equ $-err_msg
</syntaxhighlight>
</lang>


=={{header|Yorick}}==
=={{header|Yorick}}==
Yorick does not have a built-in function to recursively delete a directory; the rmdir function only works on empty directories.
Yorick does not have a built-in function to recursively delete a directory; the rmdir function only works on empty directories.
<lang yorick>remove, "input.txt";
<syntaxhighlight lang="yorick">remove, "input.txt";
remove, "/input.txt";
remove, "/input.txt";
rmdir, "docs";
rmdir, "docs";
rmdir, "/docs";</lang>
rmdir, "/docs";</syntaxhighlight>


=={{header|zig}}==
=={{header|zig}}==


<lang zig>const std = @import("std");
<syntaxhighlight lang="zig">const std = @import("std");
const fs = std.fs;
const fs = std.fs;


Line 1,757: Line 1,924:
try root.deleteFile("input.txt");
try root.deleteFile("input.txt");
try root.deleteDir("docs");
try root.deleteDir("docs");
}</lang>
}</syntaxhighlight>


=={{header|zkl}}==
=={{header|zkl}}==
zkl doesn't have built ins to delete files or directories but you can let a shell do it:
zkl doesn't have built ins to delete files or directories but you can let a shell do it:
<lang zkl>zkl: System.cmd((System.isWindows and "del" or "unlink") + " input.txt")
<syntaxhighlight lang="zkl">zkl: System.cmd((System.isWindows and "del" or "unlink") + " input.txt")
0
0
zkl: System.cmd((System.isWindows and "del" or "unlink") + " /input.txt")
zkl: System.cmd((System.isWindows and "del" or "unlink") + " /input.txt")
Line 1,773: Line 1,940:
zkl: System.cmd("rm -r /docs")
zkl: System.cmd("rm -r /docs")
rm: cannot remove ‘/docs’: No such file or directory
rm: cannot remove ‘/docs’: No such file or directory
256</lang>
256</syntaxhighlight>


{{omit from|Befunge}} <!-- No filesystem support -->
{{omit from|Befunge}} <!-- No filesystem support -->
{{omit from|EasyLang}}
{{omit from|HTML}}
{{omit from|HTML}}
{{omit from|Openscad}}
{{omit from|Openscad}}

Latest revision as of 16:07, 24 November 2023

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

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.

11l

fs:remove_file(‘output.txt’)
fs:remove_dir(‘docs’)
fs:remove_file(‘/output.txt’)
fs:remove_dir(‘/docs’)

8th

"input.txt" f:rm drop
"/input.txt" f:rm drop
"docs" f:rmdir drop
"/docs" f:rmdir drop

The 'drop' removes the result (true or false, indicating success or failure). It is not strictly necessary to do so, but it keeps the stack clean.

AArch64 Assembly

Works with: as version Raspberry Pi 3B version Buster 64 bits
/* ARM assembly AARCH64 Raspberry PI 3B */
/*  program deleteFic64.s   */

/*******************************************/
/* Constantes file                         */
/*******************************************/
/* for this file see task include a file in language AArch64 assembly*/
.include "../includeConstantesARM64.inc"

.equ UNLINK, 35

.equ AT_REMOVEDIR, 0x200           // flag for delete directory

/******************************************/
/* Initialized data                       */
/******************************************/
.data
szMessDeleteDirOk:   .asciz "Delete directory Ok.\n"
szMessErrDeleteDir:  .asciz "Unable delete dir. \n"
szMessDeleteFileOk:  .asciz "Delete file Ok.\n"
szMessErrDeleteFile: .asciz "Unable delete file. \n"

szNameDir:          .asciz "Docs"
szNameFile:         .asciz "input.txt"

/******************************************/
/* UnInitialized data                     */
/******************************************/
.bss 
/******************************************/
/*  code section                          */
/******************************************/
.text
.global main 
main:                           // entry of program 
    // delete file
    mov x0,AT_FDCWD             // current directory
    ldr x1,qAdrszNameFile       // file name
    mov x8,UNLINK               // code call system delete file
    svc 0                       // call systeme 
    cmp x0,0                    // error ?
    blt 99f
    ldr x0,qAdrszMessDeleteFileOk // delete file OK 
    bl affichageMess
                               // delete directory
    mov x0,AT_FDCWD            // current directory
    ldr x1,qAdrszNameDir       // directory name
    mov x2,AT_REMOVEDIR
    mov x8,UNLINK              // code call system delete directory 
    svc 0                      // call systeme 
    cmp x0,0                   // error ?
    blt 98f
    ldr x0,qAdrszMessDeleteDirOk // display  message ok directory
    bl affichageMess
                               // end Ok
    b 100f

98:                            // display error message delete directory 
    ldr x0,qAdrszMessErrDeleteDir
    bl affichageMess
    b 100f
99:                            // display error message delete file 
    ldr x0,qAdrszMessErrDeleteFile
    bl affichageMess
    b 100f
100:                           // standard end of the program 
    mov x0,0                   // return code
    mov x8,EXIT                // request to exit program
    svc 0                      // perform the system call
qAdrszMessDeleteDirOk:        .quad szMessDeleteDirOk
qAdrszMessErrDeleteDir:       .quad szMessErrDeleteDir
qAdrszMessDeleteFileOk:       .quad szMessDeleteFileOk
qAdrszNameFile:               .quad szNameFile
qAdrszMessErrDeleteFile:      .quad szMessErrDeleteFile
qAdrszNameDir:                .quad szNameDir
/********************************************************/
/*        File Include fonctions                        */
/********************************************************/
/* for this file see task include a file in language AArch64 assembly */
.include "../includeARM64.inc"

Action!

The attached result has been obtained under DOS 2.5.

PROC Dir(CHAR ARRAY filter)
  CHAR ARRAY line(255)
  BYTE dev=[1]

  Close(dev)
  Open(dev,filter,6)
  DO
    InputSD(dev,line)
    PrintE(line)
    IF line(0)=0 THEN
      EXIT
    FI
  OD
  Close(dev)
RETURN

PROC DeleteFile(CHAR ARRAY fname)
  BYTE dev=[1]

  Close(dev)
  Xio(dev,0,33,0,0,fname)
RETURN

PROC Main()
  CHAR ARRAY filter="D:*.*", fname="D:INPUT.TXT"

  PrintF("Dir ""%S""%E",filter)
  Dir(filter)

  PrintF("Delete file ""%S""%E%E",fname)
  DeleteFile(fname)

  PrintF("Dir ""%S""%E",filter)
  Dir(filter)
RETURN
Output:

Screenshot from Atari 8-bit computer

Dir "D:*.*"
  DOS     SYS 037
  DUP     SYS 042
  INPUT   TXT 001
627 FREE SECTORS

Delete file "D:INPUT.TXT"

Dir "D:*.*"
  DOS     SYS 037
  DUP     SYS 042
628 FREE SECTORS

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.

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")

Aime

remove("input.txt");
remove("/input.txt");
remove("docs");
remove("/docs");

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")
)

ARM Assembly

Works with: as version Raspberry Pi
/* ARM assembly Raspberry PI  */
/*  program deleteFic.s   */

/* REMARK 1 : this program use routines in a include file 
   see task Include a file language arm assembly 
   for the routine affichageMess conversion10 
   see at end of this program the instruction include */
/***************************************************************/
/* File Constantes  see task Include a file for arm assembly   */
/***************************************************************/
.include "../constantes.inc"

.equ RMDIR,  0x28
.equ UNLINK, 0xA
/******************************************/
/* Initialized data                       */
/******************************************/
.data
szMessDeleteDirOk:   .asciz "Delete directory Ok.\n"
szMessErrDeleteDir:  .asciz "Unable delete dir. \n"
szMessDeleteFileOk:  .asciz "Delete file Ok.\n"
szMessErrDeleteFile: .asciz "Unable delete file. \n"

szNameDir:          .asciz "Docs"
szNameFile:         .asciz "input.txt"

/******************************************/
/* UnInitialized data                     */
/******************************************/
.bss 
/******************************************/
/*  code section                          */
/******************************************/
.text
.global main 
main:                           @ entry of program 
    @ delete file
    ldr r0,iAdrszNameFile       @ file name

    mov r7,#UNLINK              @ code call system delete file
    svc #0                      @ call systeme 
    cmp r0,#0                   @ error ?
    blt 99f
    ldr r0,iAdrszMessDeleteFileOk @ delete file OK 
    bl affichageMess
                                @ delete directory
    ldr r0,iAdrszNameDir        @ directory name
    mov r7, #RMDIR              @ code call system delete directory 
    swi #0                      @ call systeme 
    cmp r0,#0                   @ error ?
    blt 98f
    ldr r0,iAdrszMessDeleteDirOk @ display  message ok directory
    bl affichageMess
                                @ end Ok
    b 100f

98:                             @ display error message delete directory 
    ldr r0,iAdrszMessErrDeleteDir
    bl affichageMess
    b 100f
99:                             @ display error message delete file 
    ldr r0,iAdrszMessErrDeleteFile
    bl affichageMess
    b 100f
100:                            @ standard end of the program 
    mov r0, #0                  @ return code
    mov r7, #EXIT               @ request to exit program
    swi 0                       @ perform the system call
iAdrszMessDeleteDirOk:        .int szMessDeleteDirOk
iAdrszMessErrDeleteDir:       .int szMessErrDeleteDir
iAdrszMessDeleteFileOk:       .int szMessDeleteFileOk
iAdrszNameFile:               .int szNameFile
iAdrszMessErrDeleteFile:      .int szMessErrDeleteFile
iAdrszNameDir:                .int szNameDir
/***************************************************/
/*      ROUTINES INCLUDE                 */
/***************************************************/
.include "../affichage.inc"

Arturo

file: "input.txt"
docs: "docs"

delete file
delete.directory file

delete join.path ["/" file]
delete.directory join.path ["/" docs]

AutoHotkey

FileDelete, input.txt
FileDelete, \input.txt
FileRemoveDir, docs, 1
FileRemoveDir, \docs, 1

with DllCall

Source: DeleteFile @github by jNizM

DeleteFile(lpFileName)
{
    DllCall("Kernel32.dll\DeleteFile", "Str", lpFileName)
}

DeleteFile("C:\Temp\TestFile.txt")

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")

Axe

DelVar "appvINPUT"

BASIC

Works with: QBasic
Works with: DOS

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"

Applesoft BASIC

There are disk volumes, but no folders in DOS 3.3.

 0  PRINT  CHR$ (4)"DELETE INPUT.TXT"

BaCon

BaCon has a DELETE instruction, that accepts FILE|DIRECTORY|RECURSIVE options.

DELETE FILE "input.txt"
DELETE FILE "/input.txt"

Errors can be caught with the CATCH GOTO label instruction (which allows RESUME from the labelled code section).

ZX Spectrum Basic

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"

And for disc drive of ZX Spectrum +3:

ERASE "a:INPUTTXT"

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$

IS-BASIC

100 WHEN EXCEPTION USE IOERROR
110   EXT "del input.txt"
120   EXT "del \input.txt"
130   EXT "rmdir docs"
140   EXT "rmdir \docs"
150 END WHEN 
160 HANDLER IOERROR
170   PRINT "Error in line";EXLINE
180   PRINT "*** ";EXSTRING$(EXTYPE)
190   CONTINUE 
200 END HANDLER

Batch File

del input.txt
rd /s /q docs

del \input.txt
rd /s /q \docs

Beef

using System;
using System.IO;

namespace DeleteFile {
  class Program {
    static void Main() {
      File.Delete("input.txt");
      Directory.Delete("docs");
      File.Delete("/input.txt");
      Directory.Delete("/docs");
    }
  }
}

BQN

File operations are under the system value •file in BQN.

•file.Remove "input.txt"
•file.Remove "/input.txt"
•file.RemoveDir "docs"
•file.RemoveDir "/docs"

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;
}

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);
            }
        }
    }
}

C++

#include <cstdio>
#include <direct.h>

int main() {
	remove( "input.txt" );
	remove( "/input.txt" );
	_rmdir( "docs" );
	_rmdir( "/docs" );

	return 0;
}

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")))

COBOL

COBOL 2023 added a dedicated DELETE FILE statement.

Works with: Visual COBOL
Works with: GnuCOBOL
       IDENTIFICATION DIVISION.
       PROGRAM-ID. Delete-Files.

       ENVIRONMENT DIVISION.
       INPUT-OUTPUT SECTION.
       FILE-CONTROL.
           SELECT Local-File ASSIGN TO "input.txt".
           SELECT Root-File  ASSIGN TO "/input.txt".

       DATA DIVISION.
       FILE SECTION.
       FD  Local-File.
       01  Local-Record PIC X.
       FD  Root-File.
       01  Root-Record  PIC X.

       PROCEDURE DIVISION.
           DELETE FILE Local-File
           DELETE FILE Root-File
           GOBACK.

       END PROGRAM Delete-Files.

However, in some implementations we need to use unofficial extensions to delete files, or if we want to delete directories. The following are built-in subroutines originally created as part of some of the COBOL products created by Micro Focus.

Works with: Visual COBOL
Works with: GnuCOBOL
       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.

       END PROGRAM Delete-Files.

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.

Works with: CLISP
(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:

Library: CL-FAD
(let ((path (make-pathname :directory '(:relative "docs"))))
  (cl-fad:delete-directory-and-files path))

Component Pascal

VAR
  l: Files.Locator;
BEGIN
  (* Locator is the directory *)
  l := Files.dir.This("proof");
  (* delete 'xx.txt' file, in directory 'proof'  *)
  Files.dir.Delete(l,"xx.txt");
END ...

D

Works with: D version 2
import std.file: remove;

void main() {
    remove("data.txt"); 
}
Library: Tango
import tango.io.Path;

void main() {
    remove("input.txt");
    remove("/input.txt");
    remove("docs");
    remove("/docs");
}
Library: Tango

POSIX:

import tango.stdc.posix.unistd;

void main() {
  unlink("input.txt");
  unlink("/input.txt");
  rmdir("docs");
  rmdir("/docs");
}

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;

E

<file:input.txt>.delete(null)
<file:docs>.delete(null)
<file:///input.txt>.delete(null)
<file:///docs>.delete(null)

Elena

ELENA 4.x :

import system'io;
 
public program()
{
    File.assign("output.txt").delete();
 
    File.assign("\output.txt").delete();        
 
    Directory.assign("docs").delete();
 
    Directory.assign("\docs").delete();
}

Elixir

File.rm!("input.txt")
File.rmdir!("docs")
File.rm!("/input.txt")
File.rmdir!("/docs")

Emacs Lisp

(delete-file "input.txt") 
(delete-directory "docs")
(delete-file "/input.txt") 
(delete-directory "/docs")

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" ).

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

Factor

"docs" "/docs" [ delete-tree ] bi@
"input.txt" "/input.txt" [ delete-file ] bi@

Forth

There is no means to delete directories in ANS Forth.

 s" input.txt" delete-file throw
s" /input.txt" delete-file throw

Fortran

Fortran 90

Works with: Fortran version 90 and later
 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")

Intel Fortran on Windows

Use Intel Fortran bindings to the Win32 API. Here we are using the DeleteFileA and RemoveDirectoryA functions.

program DeleteFileExample
    use kernel32
    implicit none
    print *, DeleteFile("input.txt")
    print *, DeleteFile("\input.txt")
    print *, RemoveDirectory("docs")
    print *, RemoveDirectory("\docs")
end program

Free Pascal

All required functions already exist in the RTL’s (run-time library) system unit which is shipped with every FPC (Free Pascal compiler) distribution and automatically included by every program.

program deletion(input, output, stdErr);
const
	rootDirectory = '/'; // might have to be altered for other platforms
	inputTextFilename = 'input.txt';
	docsFilename = 'docs';
var
	fd: file;
begin
	assign(fd, inputTextFilename);
	erase(fd);
	
	rmDir(docsFilename);
	
	assign(fd, rootDirectory + inputTextFilename);
	erase(fd);
	
	rmDir(rootDirectory + docsFilename);
end.

Note, depending on the {$IOChecks} compiler switch state, run-time error generation is inserted. In particular deletion of non-existent files or lack of privileges may cause an abort.

More convenient routines are sysUtils.deleteFile and sysUtils.removeDir. Both accept strings and just return, whether the operation was successful.

FreeBASIC

' FB 1.05.0 Win64
 
' delete file and empty sub-directory in current directory

Kill "input.txt"
RmDir "docs"
 
' delete file and empty sub-directory in root directory c:\
' deleting file in root requires administrative privileges in Windows 10

'Kill "c:\input.txt"
'RmDir "c:\docs"
 
Print "Press any key to quit"
Sleep

Furor

###sysinclude dir.uh
// ===================
argc 3 < { #s ."Usage: " 0 argv print SPACE 1 argv print ." filename\n" end }
2 argv 'e !istrue { #s ."The given file ( " 2 argv print ." ) doesn't exist!\n" end }
2 argv removefile
end
Usage: furor removefile.upu filename
###sysinclude dir.uh
#g argc 3 < { ."Usage: " #s 0 argv print SPACE 1 argv print SPACE ."unnecessary_directory\n" end }
2 argv 'd !istrue { ."The given directory doesn't exist! Exited.\n" }{
2 argv rmdir
}
end
Usage: furor rmdir.upu unnecessary_directory


Peri

###sysinclude standard.uh
###sysinclude args.uh
###sysinclude str.uh
###sysinclude io.uh
// ===================
#g argc 3 < { #s ."Usage: " 0 argv print SPACE 1 argv print ." filename\n" end }
2 argv 'e inv istrue { #s ."The given file ( " 2 argv print ." ) doesn't exist!\n" end }
2 argv removefile
end
Usage: peri removefile.upu filename
###sysinclude standard.uh
###sysinclude args.uh
###sysinclude str.uh
###sysinclude io.uh
#g argc 3 < { ."Usage: " #s 0 argv print SPACE 1 argv print SPACE ."unnecessary_directory\n" end }
2 argv 'd inv istrue { ."The given directory doesn't exist! Exited.\n" }{
2 argv rmdir
}
end
Usage: peri rmdir.upu unnecessary_directory

FutureBasic

include "NSLog.incl"

CFURLRef url

url = fn URLFileURLWithPath( fn StringByExpandingTildeInPath( @"~/Desktop/input.txt" ) )
if (fn FileManagerRemoveItemAtURL( url ) )
  NSLog( @"File \"intput.txt\" deleted." )
else
  NSLog( @"Unable to delete file \"input.txt\"." )
end if

url = fn URLFileURLWithPath( fn StringByExpandingTildeInPath( @"~/Desktop/docs" ) )
if (fn FileManagerRemoveItemAtURL( url ) )
  NSLog( @"Directory \"docs\" deleted." )
else
  NSLog( @"Unabled to delete directory \"docs\"." )
end if

HandleEvents

Gambas

Public Sub Main()

Kill User.home &/ "input.txt"
Rmdir User.home &/ "docs"

'Administrative privileges (sudo) would be required to mess about in Root - I'm not going there!

End

GAP

# Apparently GAP can only remove a file, not a directory
RemoveFile("input.txt");
# true
RemoveFile("docs");
# fail

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")
}

Groovy

On most *nix systems, this must be run as sudo for the files in root to be deleted. If you don't have permissions, it will silently fail to delete those files. I would recommend against running anything you find on the internet as sudo.

// Gets the first filesystem root.  On most systems this will be / or c:\
def fsRoot = File.listRoots().first()

// Create our list of files (including directories)
def files = [
        new File("input.txt"), 
        new File(fsRoot, "input.txt"), 
        new File("docs"), 
        new File(fsRoot, "docs")
]

/*
We use it.directory to determine whether each file is a regular file or directory.  If it is a directory, we delete
it with deleteDir(), otherwise we just use delete().
 */
files.each{
    it.directory ? it.deleteDir() : it.delete()
}

Haskell

import System.IO
import System.Directory

main = do
  removeFile "output.txt"
  removeDirectory "docs"
  removeFile "/output.txt"
  removeDirectory "/docs"

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)

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.

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

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'

Java

import java.io.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);
    }
}

JavaScript

Works with: JScript
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();
Works with: Node.js

Synchronous

const fs = require('fs');
fs.unlinkSync('myfile.txt');

Asynchronous

const fs = require('fs');
fs.unlink('myfile.txt', ()=>{
  console.log("Done!");
})

Joy

"input.txt" fremove
"docs" fremove
"/input.txt" fremove
"/docs" fremove.

Julia

# Delete a file
rm("input.txt")

# Delete a directory
rm("docs", recursive = true)

Kotlin

// version 1.0.6

/* testing on Windows 10 which needs administrative privileges
   to delete files from the root */
 
import java.io.File

fun main(args: Array<String>) {
    val paths = arrayOf("input.txt", "docs", "c:\\input.txt", "c:\\docs")
    var f: File
    for (path in paths) {
        f = File(path)
        if (f.delete())
            println("$path successfully deleted")
        else
            println("$path could not be deleted")
    }            
}
Output:
input.txt successfully deleted
docs successfully deleted
c:\input.txt successfully deleted
c:\docs successfully deleted

Running program again after files have been deleted:

Output:
input.txt could not be deleted
docs could not be deleted
c:\input.txt could not be deleted
c:\docs could not be deleted

LabVIEW

Library: LabVIEW_CWD

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.

Lang

# Load the IO module
# Replace "<pathToIO.lm>" with the location where the io.lm Lang module was installed to without "<" and ">"
ln.loadModule(<pathToIO.lm>)

$file1 = [[io]]::fp.openFile(input.txt)
[[io]]::fp.delete($file1)
[[io]]::fp.closeFile($file1)

$file2 = [[io]]::fp.openFile(/input.txt)
[[io]]::fp.delete($file2)
[[io]]::fp.closeFile($file2)

$dir1 = [[io]]::fp.openFile(docs)
[[io]]::fp.delete($dir1)
[[io]]::fp.closeFile($dir1)

$dir2 = [[io]]::fp.openFile(/docs)
[[io]]::fp.delete($dir2)
[[io]]::fp.closeFile($dir2)

Lasso

// delete file
local(f = file('input.txt'))
#f->delete

// delete directory
// directory must be empty before it can be successfully deleted. A failure is generated if the operation fails.
local(d = dir('docs'))
#d->delete

// delete file in root file system (requires permissions at user OS level)
local(f = file('//input.txt'))
#f->delete

// delete directory in root file system (requires permissions at user OS level)
// directory must be empty before it can be successfully deleted. A failure is generated if the operation fails.
local(d = file('//docs'))
#d->delete

Liberty BASIC

' show where we are
print DefaultDir$

' in here
kill "input.txt"
result=rmdir("Docs")

' from root
kill "\input.txt"
result=rmdir("\Docs")

Lingo

Delete file "input.txt" in cwd:

-- note: fileIO xtra is shipped with Director, i.e. an "internal"
fp = xtra("fileIO").new()
fp.openFile("input.txt", 0)
fp.delete()

Delete file "input.txt" in root of current volume:

-- note: fileIO xtra is shipped with Director, i.e. an "internal"
pd = the last char of _movie.path -- "\" for win, ":" for mac
_player.itemDelimiter = pd
vol = _movie.path.item[1]
fp = xtra("fileIO").new()
fp.openFile(vol&pd&"input.txt", 0)
fp.delete()

Deleting a directory requires a 3rd party xtra, but there are various free xtras that allow this. Here as example usage of BinFile xtra:

-- delete (empty) directory "docs" in cwd
bx_folder_delete("docs")

-- delete (empty) directory "docs" in root of current volume
pd = the last char of _movie.path -- "\" for win, ":" for mac
_player.itemDelimiter = pd
vol = _movie.path.item[1]
bx_folder_delete(vol&pd&"docs")

Locomotive Basic

|era,"input.txt"

(AMSDOS RSX command, therefore prefixed with a vertical bar. Also, there are no subdirectories in AMSDOS.)

Works with: UCB Logo

UCB Logo has no means to delete directories.

erasefile "input.txt
erasefile "/input.txt

Lua

os.remove("input.txt")
os.remove("/input.txt")
os.remove("docs")
os.remove("/docs")

Maple

FileTools:-Remove("input.txt");
FileTools:-RemoveDirectory("docs");
FileTools:-Remove("/input.txt");
FileTools:-RemoveDirectory("/docs");

Mathematica / Wolfram Language

wd = NotebookDirectory[];
DeleteFile[wd <> "input.txt"]
DeleteFile["/" <> "input.txt"]
DeleteDirectory[wd <> "docs"]
DeleteDirectory["/" <> "docs"]

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

MAXScript

There's no way to delete folders in MAXScript

-- Here
deleteFile "input.txt"
-- Root
deleteFile "\input.txt"

Mercury

:- module delete_file.
:- interface.

:- import_module io.

:- pred main(io::di, io::uo) is det.

:- implementation.

main(!IO) :-
    io.remove_file("input.txt", _, !IO),
    io.remove_file("/input.txt", _, !IO),
    io.remove_file("docs", _, !IO),
    io.remove_file("/docs", _, !IO).

Nanoquery

Translation of: Ursa
f = new(Nanoquery.IO.File)
f.delete("input.txt")
f.delete("docs")
f.delete("/input.txt")
f.delete("/docs")

Nemerle

using System;
using System.IO;
using System.Console;

module DeleteFile
{
    Main() : void
    {
        when (File.Exists("input.txt")) File.Delete("input.txt");
        try {
            when (File.Exists(@"\input.txt")) File.Delete(@"\input.txt");
        }
        catch {
            |e is UnauthorizedAccessException => WriteLine(e.Message)
        }
        
        when (Directory.Exists("docs")) Directory.Delete("docs");
        when (Directory.Exists(@"\docs")) Directory.Delete(@"\docs");
    }
}

NetRexx

/* NetRexx */
options replace format comments java crossref symbols binary

runSample(arg)
return

-- . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
method isFileDeleted(fn) public static returns boolean
  ff = File(fn)
  fDeleted = ff.delete()
  return fDeleted

-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
method runSample(arg) private static
  parse arg files
  if files = '' then files = 'input.txt F docs D /input.txt F /docs D'
  loop while files.length > 0
    parse files fn ft files
    select case(ft.upper())
      when 'F' then do
        ft = 'File'
        end
      when 'D' then do
        ft = 'Directory'
        end
      otherwise do
        ft = 'File'
        end
      end
    if isFileDeleted(fn) then dl = 'deleted'
    else                      dl = 'not deleted'
    say ft ''''fn'''' dl
    end

  return

NewLISP

(delete-file "input.txt")
(delete-file "/input.txt")
(remove-dir "docs")
(remove-dir "/docs")

Nim

import os
removeFile("input.txt")
removeFile("/input.txt")
removeDir("docs")
removeDir("/docs")

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");
    }
  }
}

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];

OCaml

Sys.remove "input.txt";;
Sys.remove "/input.txt";;
Sys.rmdir "docs";;
Sys.rmdir "/docs";;

with the Unix library:

#load "unix.cma";;
Unix.unlink "input.txt";;
Unix.unlink "/input.txt";;
Unix.rmdir "docs";;
Unix.rmdir "/docs";;

ooRexx

/*REXX pgm deletes a file */
file= 'afile.txt'                     /*name of a file  to be deleted.*/
res=sysFileDelete(file); Say file 'res='res
File= 'bfile.txt'                     /*name of a file  to be deleted.*/
res=sysFileDelete(file); Say file 'res='res
Output:
afile.txt res=0
bfile.txt res=2

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

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.

Pascal

See Delphi or Free Pascal

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"'

Phix

without js -- (file i/o)
constant root = iff(platform()=LINUX?"/":"C:\\")
?delete_file("input.txt")
?delete_file(root&"input.txt")
?remove_directory("docs")
?remove_directory(root&"docs")

output is 0 0 0 0 or 1 1 1 1 or some combination thereof

PHP

<?php
unlink('input.txt');
unlink('/input.txt');
rmdir('docs');
rmdir('/docs');
?>

Picat

Works with: Picat
import os.

del(Arg), directory(Arg) =>
    rmdir(Arg).

del(Arg), file(Arg) =>
    rm(Arg).

main(Args) =>
    foreach (Arg in Args)
        del(Arg)
    end.
Output:
picat delete_file.pi input.txt docs/ /input.txt /docs/

PicoLisp

(call 'rm "input.txt")
(call 'rmdir "docs")
(call 'rm "/input.txt")
(call 'rmdir "/docs")

Pike

int main(){
   rm("input.txt");
   rm("/input.txt");
   rm("docs");
   rm("/docs");
}

Plain English

To run:
Start up.
\ In the current working directory
Destroy ".\input.txt" in the file system.
Destroy ".\docs\" in the file system.
\ In the filesystem root
Destroy "C:\input.txt" in the file system.
Destroy "C:\docs\" in the file system.
Shut down.

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

ProDOS

Because input.txt is located inside of "docs" this will delete it when it deletes "docs"

deletedirectory docs

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

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")

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 ?)

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"))

Raku

(formerly Perl 6)

unlink 'input.txt';
unlink '/input.txt';
rmdir 'docs';
rmdir '/docs';

Raven

'input.txt'  delete
'/input.txt' delete
'docs'  rmdir
'/docs' rmdir

REBOL

; Local.
delete %input.txt
delete-dir %docs/

; Root.
delete %/input.txt
delete-dir %/docs/

Retro

'input.txt file:delete
'/input.txt file:delete

REXX

Note that this REXX program will work on the Next family of Microsoft Windows systems as well as DOS   (both under Windows in a DOS-prompt window or stand-alone DOS).

/*REXX program deletes a file and a folder in the  current directory  and  the root.    */
trace off                                        /*suppress REXX error messages from DOS*/
aFile= 'input.txt'                               /*name of a  file  to be deleted.      */
aDir = 'docs'                                    /*name of a folder to be removed.      */
               do j=1  for 2                     /*perform this  DO  loop exactly twice.*/
               'ERASE'  aFile                    /*erase this  file in the current dir. */
               'RMDIR'  "/s /q"  aDir            /*remove the folder "  "     "     "   */
               if j==1  then 'CD \'              /*make the  current dir  the  root dir.*/
               end                               /* [↑]  just do   CD \    command once.*/
                                                 /*stick a fork in it,  we're all done. */

Ring

remove("output.txt")
system("rmdir docs")

RPL

There is a unique RPL instruction to delete both files and directories. Directories must be empty to be deletable.

'output.txt' PURGE
'docs' PURGE
HOME output.txt' PURGE
HOME 'docs' PURGE

Basically, HOME moves the user from the current directory to the root. If the last two commands are done successively, only the first call is necessary.

Ruby

File.delete("output.txt", "/output.txt")
Dir.delete("docs")
Dir.delete("/docs")

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

Rust

use std::io::{self, Write};
use std::fs::{remove_file,remove_dir};
use std::path::Path;
use std::{process,display};
 
const FILE_NAME: &'static str = "output.txt";
const DIR_NAME : &'static str = "docs";
 
fn main() {
    delete(".").and(delete("/"))
               .unwrap_or_else(|e| error_handler(e,1));
}
 
 
fn delete<P>(root: P) -> io::Result<()>
    where P: AsRef<Path>
{
    remove_file(root.as_ref().join(FILE_NAME))
        .and(remove_dir(root.as_ref().join(DIR_NAME)))
}
 
fn error_handler<E: fmt::Display>(error: E, code: i32) -> ! {
    let _ = writeln!(&mut io::stderr(), "{:?}", error);
    process::exit(code)
}

Scala

Library: Scala
import java.util._
import java.io.File

object FileDeleteTest extends App {
  def deleteFile(filename: String) = { new File(filename).delete() }

  def test(typ: String, filename: String) = {
    System.out.println("The following " + typ + " called " + filename +
      (if (deleteFile(filename)) " was deleted." else " could not be deleted."))
  }
  test("file", "input.txt")
  test("file", File.separatorChar + "input.txt")
  test("directory", "docs")
  test("directory", File.separatorChar + "docs" + File.separatorChar)
}

Scheme

Works with: Scheme version R6RS

[1]

(delete-file filename)

Seed7

The library osfiles.s7i provides the functions removeFile and removeTree. RemoveFile removes a file of any type unless it is a directory that is not empty. RemoveTree remove a file of any type inclusive a directory tree. Note that removeFile and removeTree fail with the exception FILE_ERROR when the file does not exist.

$ include "seed7_05.s7i";
  include "osfiles.s7i";

const proc: main is func
  begin
    removeFile("input.txt");
    removeFile("/input.txt");
    removeTree("docs");
    removeTree("/docs");
  end func;

SenseTalk

// Delete locally (relative to "the folder")
delete file "input.txt"
delete folder "docs"

// Delete at the file system root
delete file "/input.txt"
delete folder "/docs"

Sidef

# here
%f'input.txt' -> delete;
%d'docs'      -> delete;

# root dir
Dir.root + %f'input.txt' -> delete;
Dir.root + %d'docs'      -> delete;

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.

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'

Standard ML

OS.FileSys.remove "input.txt";
OS.FileSys.remove "/input.txt";
OS.FileSys.rmDir "docs";
OS.FileSys.rmDir "/docs";

Stata

erase input.txt
rmdir docs

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

Toka

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

TUSCRIPT

$$ MODE TUSCRIPT
- delete file
SET status = DELETE ("input.txt")
- delete directory
SET status = DELETE ("docs",-std-)

UNIX Shell

rm -rf docs
rm input.txt
rm -rf /docs
rm /input.txt

Ursa

decl file f
f.delete "input.txt"
f.delete "docs"
f.delete "/input.txt"
f.delete "/docs"

VAX Assembly

74 75 70 6E 69 20 65 74 65 6C 65 64  0000     1 dcl:	.ascii	"delete input.txt;,docs.dir;"
64 2E 73 63 6F 64 2C 3B 74 78 74 2E  000C       
                           3B 72 69  0018       
69 76 65 64 73 79 73 24 73 79 73 2C  001B     2 	.ascii	",sys$sysdevice:[000000]input.txt;"
69 5D 30 30 30 30 30 30 5B 3A 65 63  0027       
         3B 74 78 74 2E 74 75 70 6E  0033       
69 76 65 64 73 79 73 24 73 79 73 2C  003C     3 	.ascii	",sys$sysdevice:[000000]docs.dir;"
64 5D 30 30 30 30 30 30 5B 3A 65 63  0048       
            3B 72 69 64 2E 73 63 6F  0054       
                                     005C     4 
                           0000005C  005C     5 desc:	.long	.-dcl					;character count
                           00000000' 0060     6 	.address dcl
                                     0064     7 
                               0000  0064     8 .entry	main,0
                         F3 AF   7F  0066     9 	pushaq	desc
              00000000'GF   01   FB  0069    10 	calls	#1, g^lib$do_command			;execute shell command
                                 04  0070    11 	ret
                                     0071    12 .end	main

VBA

Option Explicit

Sub DeleteFileOrDirectory()
Dim myPath As String
    myPath = "C:\Users\surname.name\Desktop\Docs"
'delete file
    Kill myPath & "\input.txt"
'delete Directory
    RmDir myPath
End Sub

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

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")

Visual Basic .NET

Platform: .NET

Works with: Visual Basic .NET version 9.0+
'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")

V (Vlang)

import os

fn main() {
	os.rm("./input.txt") or {println(err) exit(-1)}
	os.rmdir("./docs") or {println(err) exit(-2)} // os.rmdir_all, recursively removes specified directory
	// check if file exists
	if os.is_file("./input.txt") == true {println("Found file!")}
	else {println("File was not found!")}
	// check if directory exists
	if os.is_dir("./docs") == true {println("Found directory!")}
	else {println("Directory was not found!")}
}

Wren

To remove a file from the root, assuming you have the necessary privileges, just change "input.txt" to "/input.txt" in the following script.

Wren does not currently support the removal of directories.

import "io" for File

File.delete("input.txt")

// check it worked
System.print(File.exists("input.txt"))
Output:
false

X86 Assembly

Works with: NASM version Linux
;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 'input.txt',0
rfn		db '/input.txt',0
dn		db 'doc',0

err_msg		db "Something went wrong! :[",0xa
err_len		equ $-err_msg

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";

zig

const std = @import("std");
const fs = std.fs;

pub fn main() !void {
    const here = fs.cwd();
    try here.deleteFile("input.txt");
    try here.deleteDir("docs");

    const root = try fs.openDirAbsolute("/", .{});
    try root.deleteFile("input.txt");
    try root.deleteDir("docs");
}

zkl

zkl doesn't have built ins to delete files or directories but you can let a shell do it:

zkl: System.cmd((System.isWindows and "del" or "unlink") + " input.txt")
0
zkl: System.cmd((System.isWindows and "del" or "unlink") + " /input.txt")
unlink: cannot unlink ‘/input.txt’: No such file or directory
256
zkl: System.cmd("rmdir docs")
rmdir: failed to remove ‘docs’: Directory not empty
256
zkl: System.cmd("rm -r docs")
0
zkl: System.cmd("rm -r /docs")
rm: cannot remove ‘/docs’: No such file or directory
256