Delete a file

From Rosetta Code
(Redirected from File Delete)
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[edit]

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

8th[edit]

"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[edit]

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![edit]

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[edit]

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[edit]

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[edit]

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

ALGOL 68[edit]

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[edit]

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[edit]

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

delete file
delete.directory file

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

AutoHotkey[edit]

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

with DllCall[edit]

Source: DeleteFile @github by jNizM

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

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

AWK[edit]

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[edit]

DelVar "appvINPUT"

BASIC[edit]

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[edit]

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

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

BaCon[edit]

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[edit]

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[edit]

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[edit]

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[edit]

del input.txt
rd /s /q docs

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

Beef[edit]

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[edit]

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[edit]

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#[edit]

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++[edit]

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

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

	return 0;
}

Clojure[edit]

(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[edit]

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: OpenCOBOL
       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
           .

Alternate method of deleting files using the DELETE FILE statement.

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

       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
           .

Common Lisp[edit]

(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[edit]

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[edit]

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[edit]

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[edit]

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

Elena[edit]

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[edit]

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

Emacs Lisp[edit]

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

Erlang[edit]

-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#[edit]

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[edit]

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

Forth[edit]

There is no means to delete directories in ANS Forth.

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

Fortran[edit]

Fortran 90[edit]

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[edit]

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[edit]

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[edit]

' 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[edit]

###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

FutureBasic[edit]

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[edit]

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[edit]

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

Go[edit]

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[edit]

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[edit]

import System.IO
import System.Directory

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

HicEst[edit]

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[edit]

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[edit]

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[edit]

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[edit]

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[edit]

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

Julia[edit]

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

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

Kotlin[edit]

// 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[edit]

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.
LabVIEW Delete a file.png

Lasso[edit]

// 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[edit]

' show where we are
print DefaultDir$

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

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

Lingo[edit]

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[edit]

|era,"input.txt"

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

[edit]

Works with: UCB Logo

UCB Logo has no means to delete directories.

erasefile "input.txt
erasefile "/input.txt

Lua[edit]

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

Maple[edit]

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

Mathematica / Wolfram Language[edit]

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

MATLAB / Octave[edit]

   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[edit]

There's no way to delete folders in MAXScript

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

Mercury[edit]

:- 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[edit]

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

Nemerle[edit]

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[edit]

/* 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[edit]

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

Nim[edit]

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

Objeck[edit]

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[edit]

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[edit]

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[edit]

/*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[edit]

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[edit]

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[edit]

See Delphi or Free Pascal

Perl[edit]

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[edit]

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[edit]

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

Picat[edit]

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[edit]

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

Pike[edit]

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

Plain English[edit]

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[edit]

# 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[edit]

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

deletedirectory docs

PureBasic[edit]

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[edit]

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[edit]

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[edit]

#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[edit]

(formerly Perl 6)

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

Raven[edit]

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

REBOL[edit]

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

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

Retro[edit]

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

REXX[edit]

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[edit]

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

Ruby[edit]

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

Run BASIC[edit]

'------ 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[edit]

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[edit]

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[edit]

Works with: Scheme version R6RS
[1]
(delete-file filename)

Seed7[edit]

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[edit]

// 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[edit]

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

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

Slate[edit]

(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[edit]

(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[edit]

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

Stata[edit]

erase input.txt
rmdir docs

Tcl[edit]

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[edit]

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

TUSCRIPT[edit]

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

UNIX Shell[edit]

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

Ursa[edit]

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

VAX Assembly[edit]

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[edit]

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[edit]

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[edit]

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[edit]

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

Wren[edit]

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[edit]

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[edit]

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[edit]

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[edit]

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