
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.
fs:remove_file(‘output.txt’)fs:remove_dir(‘docs’)fs:remove_file(‘/output.txt’)fs:remove_dir(‘/docs’)
"input.txt"f:rmdrop"/input.txt"f:rmdrop"docs"f:rmdirdrop"/docs"f:rmdirdrop
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.
/* 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 *//******************************************/.dataszMessDeleteDirOk: .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 100f98: // display error message delete directory ldr x0,qAdrszMessErrDeleteDir bl affichageMess b 100f99: // display error message delete file ldr x0,qAdrszMessErrDeleteFile bl affichageMess b 100f100: // standard end of the program mov x0,0 // return code mov x8,EXIT // request to exit program svc 0 // perform the system callqAdrszMessDeleteDirOk: .quad szMessDeleteDirOkqAdrszMessErrDeleteDir: .quad szMessErrDeleteDirqAdrszMessDeleteFileOk: .quad szMessDeleteFileOkqAdrszNameFile: .quad szNameFileqAdrszMessErrDeleteFile: .quad szMessErrDeleteFileqAdrszNameDir: .quad szNameDir/********************************************************//* File Include fonctions *//********************************************************//* for this file see task include a file in language AArch64 assembly */.include "../includeARM64.inc"
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)RETURNPROC DeleteFile(CHAR ARRAY fname) BYTE dev=[1] Close(dev) Xio(dev,0,33,0,0,fname)RETURNPROC 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)RETURNScreenshot from Atari 8-bit computer
Dir "D:*.*" DOS SYS 037 DUP SYS 042 INPUT TXT 001627 FREE SECTORSDelete file "D:INPUT.TXT"Dir "D:*.*" DOS SYS 037 DUP SYS 042628 FREE SECTORS
withAda.Directories;useAda.Directories;
and then
Delete_File("input.txt");Delete_File("/input.txt");Delete_Tree("docs");Delete_Tree("/docs");
Naming conventions for the file path areOS-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 underLinux andWindows.
Theremove 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")remove("input.txt");remove("/input.txt");remove("docs");remove("/docs");The Algol 68 prelude routine "scratch" can only delete temporary files, so we have to resort to running OS commands...
Unfortunately, this is, of course operating system dependant - the sample below is for Windows - the commands and value of root should be changed for your system.
E.g.: for Unix/Linux systems the value of root should be / and the del command replaced-by rm, rmdir by rm -r.
Note Windows rmdir will only delete empty directories.
Additionally, system isn't a standard Algol 68 prelude routine, so this relies on theALGOL 68 Genie extension.
BEGIN # note the pathnames and commands are Windows specific - adjust for other systems # STRING root = "\", del = "del ", rmdir = "rmdir "; PROC remove file = (STRING file name)INT: system( del + file name ); PROC remove dir = (STRING file name)INT: system(rmdir + file name ); PROC report error = ( STRING message )VOID: print( ( message, newline ) ); IF remove file("input.txt") NE 0 THEN report error( "Unable to remove input.txt" ) FI; IF remove file(root + "input.txt") NE 0 THEN report error( "Unable to remove " + root + "input.txt" ) FI; IF remove dir("docs") NE 0 THEN report error( "Unable to remove docs" ) FI; IF remove dir(root + "docs") NE 0 THEN report error( "Unable to remove " + root + "docs" ) FIEND# io:removeFiles can take multiple path to delete(io:removeFiles "input.txt" "/input.txt")(io:removeFiles "docs" "/docs")# or just one(io:removeFiles "input.txt")(io:removeFiles "/input.txt")(io:removeFiles "docs")(io:removeFiles "/docs")
/* 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 *//******************************************/.dataszMessDeleteDirOk: .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 100f98: @ display error message delete directory ldr r0,iAdrszMessErrDeleteDir bl affichageMess b 100f99: @ display error message delete file ldr r0,iAdrszMessErrDeleteFile bl affichageMess b 100f100: @ standard end of the program mov r0, #0 @ return code mov r7, #EXIT @ request to exit program swi 0 @ perform the system calliAdrszMessDeleteDirOk: .int szMessDeleteDirOkiAdrszMessErrDeleteDir: .int szMessErrDeleteDiriAdrszMessDeleteFileOk: .int szMessDeleteFileOkiAdrszNameFile: .int szNameFileiAdrszMessErrDeleteFile: .int szMessErrDeleteFileiAdrszNameDir: .int szNameDir/***************************************************//* ROUTINES INCLUDE *//***************************************************/.include "../affichage.inc"
file:"input.txt"docs:"docs"deletefiledelete.directoryfiledeletejoin.path["/"file]delete.directoryjoin.path["/"docs]
FileDelete,input.txtFileDelete, \input.txtFileRemoveDir,docs,1FileRemoveDir, \docs,1
Source:DeleteFile @github by jNizM
DeleteFile(lpFileName){DllCall("Kernel32.dll\DeleteFile","Str",lpFileName)}DeleteFile("C:\Temp\TestFile.txt")
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")
DelVar "appvINPUT"
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"
There are disk volumes, but no folders in DOS 3.3.
0PRINTCHR$(4)"DELETE INPUT.TXT"
BaCon has aDELETE instruction, that acceptsFILE|DIRECTORY|RECURSIVE options.
DELETEFILE"input.txt"DELETEFILE"/input.txt"
Errors can be caught with theCATCH GOTO label instruction (which allowsRESUME from the labelled code section).
The ZX Spectrum microdrive had only a main directory, and filenames did not havefile 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"
If the names are known as constants at compile time:
*DELETEinput.txt*DELETE\input.txt*RMDIRdocs*RMDIR\docs
If the names are known only at run time:
OSCLI "DELETE " + file$ OSCLI "RMDIR " + dir$
100 WHEN EXCEPTION USE IOERROR110 EXT "del input.txt"120 EXT "del \input.txt"130 EXT "rmdir docs"140 EXT "rmdir \docs"150 END WHEN 160 HANDLER IOERROR170 PRINT "Error in line";EXLINE180 PRINT "*** ";EXSTRING$(EXTYPE)190 CONTINUE 200 END HANDLER
echo n ensures that wheneverdel prompt to delete a directory, it would deny.
The/f flag forces deleting read-only files (not directories).
@echo offecho n|del /f input.txtrd /s /q docsecho n|del /f \input.txtrd /s /q \docs
usingSystem;usingSystem.IO;namespaceDeleteFile{classProgram{staticvoidMain(){File.Delete("input.txt");Directory.Delete("docs");File.Delete("/input.txt");Directory.Delete("/docs");}}}
File operations are under the system value•file in BQN.
•file.Remove"input.txt"•file.Remove"/input.txt"•file.RemoveDir"docs"•file.RemoveDir"/docs"
ISO C:
#include<stdio.h>intmain(){remove("input.txt");remove("/input.txt");remove("docs");remove("/docs");return0;}
POSIX:
#include<unistd.h>intmain(){unlink("input.txt");unlink("/input.txt");rmdir("docs");rmdir("/docs");return0;}
usingSystem;usingSystem.IO;namespaceRosettaCode{classProgram{staticvoidMain(){try{File.Delete("input.txt");Directory.Delete("docs");File.Delete(@"\input.txt");Directory.Delete(@"\docs");}catch(Exceptionexception){Console.WriteLine(exception.Message);}}}}
#include<cstdio>#include<direct.h>intmain(){remove("input.txt");remove("/input.txt");_rmdir("docs");_rmdir("/docs");return0;}
(import'(java.ioFile))(.delete(File."output.txt"))(.delete(File."docs"))(.delete(newFile(str(File/separator)"output.txt")))(.delete(newFile(str(File/separator)"docs")))
COBOL 2023 added a dedicatedDELETE FILE statement.
IDENTIFICATIONDIVISION.PROGRAM-ID.Delete-Files.ENVIRONMENTDIVISION.INPUT-OUTPUTSECTION.FILE-CONTROL.SELECTLocal-FileASSIGNTO"input.txt".SELECTRoot-FileASSIGNTO"/input.txt".DATADIVISION.FILESECTION.FDLocal-File.01Local-RecordPIC X.FDRoot-File.01Root-RecordPIC X.PROCEDUREDIVISION.DELETEFILELocal-FileDELETEFILERoot-FileGOBACK.ENDPROGRAMDelete-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.
IDENTIFICATIONDIVISION.PROGRAM-ID.Delete-Files.PROCEDUREDIVISION.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.ENDPROGRAMDelete-Files.
(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 isext:delete-dir.
(let((path(make-pathname:directory'(:relative"docs"))))(ext:delete-dirpath))(let((path(make-pathname:directory'(:absolute"docs"))))(ext:delete-dirpath))
Or you can use the portability library CL-FAD:
(let((path(make-pathname:directory'(:relative"docs"))))(cl-fad:delete-directory-and-filespath))
VARl: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...
importstd.file:remove;voidmain(){remove("data.txt");}
importtango.io.Path;voidmain(){remove("input.txt");remove("/input.txt");remove("docs");remove("/docs");}
POSIX:
importtango.stdc.posix.unistd;voidmain(){unlink("input.txt");unlink("/input.txt");rmdir("docs");rmdir("/docs");}
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;<file:input.txt>.delete(null)<file:docs>.delete(null)<file:///input.txt>.delete(null)<file:///docs>.delete(null)
# by Artyom Bologov# Write nothing to the file.# That's the best one can do with ed native APIs.,dw input.txt# Invoking the shell.# More reliable but surrendering to the OS.!rm input.txt!rm -r docs/!rm /input.txt!rm -r /docs/Q
ELENA 6.x :
import system'io; public Program(){ File.assign("output.txt").delete(); File.assign("\output.txt").delete(); Directory.assign("docs").delete(); Directory.assign("\docs").delete();}File.rm!("input.txt")File.rmdir!("docs")File.rm!("/input.txt")File.rmdir!("/docs")
(delete-file"input.txt")(delete-directory"docs")(delete-file"/input.txt")(delete-directory"/docs")
-module(delete).-export([main/0]).main()->% current directoryok=file:del_dir("docs"),ok=file:delete("input.txt"),% root directoryok=file:del_dir("/docs"),ok=file:delete("/input.txt").
openSystem.IO[<EntryPoint>]letmainargv=letfileName="input.txt"letdirName="docs"forpathin[".";"/"]doignore(File.Delete(Path.Combine(path,fileName)))ignore(Directory.Delete(Path.Combine(path,dirName)))0
"docs""/docs"[delete-tree]bi@"input.txt""/input.txt"[delete-file]bi@
There is no means to delete directories in ANS Forth.
s"input.txt"delete-filethrows"/input.txt"delete-filethrow
OPEN(UNIT=5,FILE="input.txt",STATUS="OLD")! Current directoryCLOSE(UNIT=5,STATUS="DELETE")OPEN(UNIT=5,FILE="/input.txt",STATUS="OLD")! Root directoryCLOSE(UNIT=5,STATUS="DELETE")
Use Intel Fortran bindings to the Win32 API. Here we are using theDeleteFileA andRemoveDirectoryA functions.
programDeleteFileExampleusekernel32implicit none print*,DeleteFile("input.txt")print*,DeleteFile("\input.txt")print*,RemoveDirectory("docs")print*,RemoveDirectory("\docs")end program
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.
programdeletion(input,output,stdErr);constrootDirectory='/';// might have to be altered for other platformsinputTextFilename='input.txt';docsFilename='docs';varfd:file;beginassign(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 aresysUtils.deleteFile andsysUtils.removeDir.Both accept strings and just return, whether the operation was successful.
' FB 1.05.0 Win64' delete file and empty sub-directory in current directoryKill"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
###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 removefileendUsage: 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}endUsage: furor rmdir.upu unnecessary_directory
###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 removefileendUsage: 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}endUsage: peri rmdir.upu unnecessary_directory
include "NSLog.incl"CFURLRef urlurl = 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 ifurl = fn URLFileURLWithPath( fn StringByExpandingTildeInPath( @"~/Desktop/docs" ) )if (fn FileManagerRemoveItemAtURL( url ) ) NSLog( @"Directory \"docs\" deleted." )else NSLog( @"Unabled to delete directory \"docs\"." )end ifHandleEvents
PublicSubMain()KillUser.home&/"input.txt"RmdirUser.home&/"docs"'Administrative privileges (sudo) would be required to mess about in Root - I'm not going there!End
# Apparently GAP can only remove a file, not a directoryRemoveFile("input.txt");# trueRemoveFile("docs");# fail
packagemainimport"os"funcmain(){os.Remove("input.txt")os.Remove("/input.txt")os.Remove("docs")os.Remove("/docs")// recursively removes contents:os.RemoveAll("docs")os.RemoveAll("/docs")}
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:\deffsRoot=File.listRoots().first()// Create our list of files (including directories)deffiles=[newFile("input.txt"),newFile(fsRoot,"input.txt"),newFile("docs"),newFile(fsRoot,"docs")]/*We use it.directory to determine whether each file is a regular file or directory. If it is a directory, we deleteit with deleteDir(), otherwise we just use delete(). */files.each{it.directory?it.deleteDir():it.delete()}
importSystem.IOimportSystem.Directorymain=doremoveFile"output.txt"removeDirectory"docs"removeFile"/output.txt"removeDirectory"/docs"
SYSTEM(DIR="docs") ! create docs in current directory (if not existent), make it currentOPEN (FILE="input.txt", "NEW") ! in current directory = docsWRITE(FIle="input.txt", DELETE=1) ! no command to DELETE a DIRECTORY in HicEstSYSTEM(DIR="C:\docs") ! create C:\docs (if not existent), make it currentOPEN (FILE="input.txt", "NEW") ! in current directory = C:\docsWRITE(FIle="input.txt", DELETE=1)
Icon supports 'remove' for files.
everydir:=!["./","/"]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.
DirectoryfileNamed("input.txt")removeDirectorydirectoryNamed("docs")removeRootDir:=DirectoryclonesetPath("/")RootDirfileNamed("input.txt")removeRootDirdirectoryNamed("docs")remove
or
Filewith("input.txt")removeDirectorywith("docs")removeFilewith("/input.txt")removeDirectorywith("/docs")remove
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 thefiles library like so:
NB. =========================================================NB.*ferase v erases a fileNB. Returns 1 if successful, otherwise _1ferase=:(1!:55::_1:)@(fboxname&>)@boxopen
This means that you can directly erase files and directories without loading thefiles library.
1!:55<'input.txt'1!:55<'\input.txt'1!:55<'docs'1!:55<'\docs'
importjava.io.File;publicclassFileDeleteTest{publicstaticbooleandeleteFile(Stringfilename){booleanexists=newFile(filename).delete();returnexists;}publicstaticvoidtest(Stringtype,Stringfilename){System.out.println("The following "+type+" called "+filename+(deleteFile(filename)?" was deleted.":" could not be deleted."));}publicstaticvoidmain(Stringargs[]){test("file","input.txt");test("file",File.seperator+"input.txt");test("directory","docs");test("directory",File.seperator+"docs"+File.seperator);}}
importjava.io.IOException;importjava.nio.file.Files;importjava.nio.file.Path;publicfinalclassDeleteAFile{publicstaticvoidmain(String[]args)throwsIOException{Files.delete(Path.of("output.txt"));Files.delete(Path.of("docs"));Files.delete(Path.of("/output.txt"));Files.delete(Path.of("/docs"));}}
varfso=newActiveXObject("Scripting.FileSystemObject");fso.DeleteFile('input.txt');fso.DeleteFile('c:/input.txt');fso.DeleteFolder('docs');fso.DeleteFolder('c:/docs');
or
varfso=newActiveXObject("Scripting.FileSystemObject");varf;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();
Synchronous
constfs=require('fs');fs.unlinkSync('myfile.txt');
Asynchronous
constfs=require('fs');fs.unlink('myfile.txt',()=>{console.log("Done!");})
"input.txt" fremove"docs" fremove"/input.txt" fremove"/docs" fremove.
# Delete a filerm("input.txt")# Delete a directoryrm("docs",recursive=true)
// version 1.0.6/* testing on Windows 10 which needs administrative privileges to delete files from the root */importjava.io.Filefunmain(args:Array<String>){valpaths=arrayOf("input.txt","docs","c:\\input.txt","c:\\docs")varf:Filefor(pathinpaths){f=File(path)if(f.delete())println("$path successfully deleted")elseprintln("$path could not be deleted")}}
input.txt successfully deleteddocs successfully deletedc:\input.txt successfully deletedc:\docs successfully deleted
Running program again after files have been deleted:
input.txt could not be deleteddocs could not be deletedc:\input.txt could not be deletedc:\docs could not be deleted
This image is aVI Snippet, an executable image ofLabVIEW 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.
# 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)
// delete filelocal(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
' show where we areprint DefaultDir$' in herekill "input.txt"result=rmdir("Docs")' from rootkill "\input.txt"result=rmdir("\Docs")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 = pdvol = _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 cwdbx_folder_delete("docs")-- delete (empty) directory "docs" in root of current volumepd = the last char of _movie.path -- "\" for win, ":" for mac_player.itemDelimiter = pdvol = _movie.path.item[1]bx_folder_delete(vol&pd&"docs")|era,"input.txt"
(AMSDOS RSX command, therefore prefixed with a vertical bar. Also, there are no subdirectories in AMSDOS.)
UCB Logo has no means to delete directories.
erasefile "input.txterasefile "/input.txt
os.remove("input.txt")os.remove("/input.txt")os.remove("docs")os.remove("/docs")
FileTools:-Remove("input.txt");FileTools:-RemoveDirectory("docs");FileTools:-Remove("/input.txt");FileTools:-RemoveDirectory("/docs");
wd=NotebookDirectory[];DeleteFile[wd<>"input.txt"]DeleteFile["/"<>"input.txt"]DeleteDirectory[wd<>"docs"]DeleteDirectory["/"<>"docs"]
delete('input.txt');% delete local file input.txtdelete('/input.txt');% delete file /input.txtrmdir('docs');% remove local directory docsrmdir('/docs');% remove directory /docs
On Unix-Systems:
ifsystem('rm input.txt')==0disp('input.txt removed')endifsystem('rm /input.txt')==0disp('/input.txt removed')endifsystem('rmdir docs')==0disp('docs removed')endifsystem('rmdir /docs')==0disp('/docs removed')end
load("operatingsystem")$delete_file("output.txt")$delete_file("/output.txt")$rmdir("docs")$rmdir("/docs")$
There's no way to delete folders in MAXScript
-- HeredeleteFile "input.txt"-- RootdeleteFile "\input.txt"
:- 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).f = new(Nanoquery.IO.File)f.delete("input.txt")f.delete("docs")f.delete("/input.txt")f.delete("/docs")usingSystem;usingSystem.IO;usingSystem.Console;moduleDeleteFile{Main():void{when(File.Exists("input.txt"))File.Delete("input.txt");try{when(File.Exists(@"\input.txt"))File.Delete(@"\input.txt");}catch{|eisUnauthorizedAccessException=>WriteLine(e.Message)}when(Directory.Exists("docs"))Directory.Delete("docs");when(Directory.Exists(@"\docs"))Directory.Delete(@"\docs");}}
/* NetRexx */optionsreplaceformatcommentsjavacrossrefsymbolsbinaryrunSample(arg)return--.......................................methodisFileDeleted(fn)publicstaticreturnsbooleanff=File(fn)fDeleted=ff.delete()returnfDeleted--~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~methodrunSample(arg)privatestaticparseargfilesiffiles=''thenfiles='input.txt F docs D /input.txt F /docs D'loopwhilefiles.length>0parsefilesfnftfilesselectcase(ft.upper())when'F'thendoft='File'endwhen'D'thendoft='Directory'endotherwisedoft='File'endendifisFileDeleted(fn)thendl='deleted'elsedl='not deleted'sayft''''fn''''dlendreturn
(delete-file"input.txt")(delete-file"/input.txt")(remove-dir"docs")(remove-dir"/docs")
importosremoveFile("input.txt")removeFile("/input.txt")removeDir("docs")removeDir("/docs")
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"); } }}NSFileManager*fm=[NSFileManagerdefaultManager];// Pre-OS X 10.5[fmremoveFileAtPath:@"input.txt"handler:nil];[fmremoveFileAtPath:@"/input.txt"handler:nil];[fmremoveFileAtPath:@"docs"handler:nil];[fmremoveFileAtPath:@"/docs"handler:nil];// OS X 10.5+[fmremoveItemAtPath:@"input.txt"error:NULL];[fmremoveItemAtPath:@"/input.txt"error:NULL];[fmremoveItemAtPath:@"docs"error:NULL];[fmremoveItemAtPath:@"/docs"error:NULL];
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";;
/*REXX pgm deletes a file */file='afile.txt'/*name of a file to be deleted.*/res=sysFileDelete(file);Sayfile'res='resFile='bfile.txt'/*name of a file to be deleted.*/res=sysFileDelete(file);Sayfile'res='res
afile.txt res=0bfile.txt res=2
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."} endendGP 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 standardC methods.
SeeDelphi orFree Pascal
useFile::Spec::Functionsqw(catfile rootdir);# hereunlink'input.txt';rmdir'docs';# root dirunlinkcatfilerootdir,'input.txt';rmdircatfilerootdir,'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"'
withoutjs-- (file i/o)constantroot=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
<?phpunlink('input.txt');unlink('/input.txt');rmdir('docs');rmdir('/docs');?>
import os.del(Arg), directory(Arg) => rmdir(Arg).del(Arg), file(Arg) => rm(Arg).main(Args) => foreach (Arg in Args) del(Arg) end.
picat delete_file.pi input.txt docs/ /input.txt /docs/
(call 'rm "input.txt")(call 'rmdir "docs")(call 'rm "/input.txt")(call 'rmdir "/docs")
intmain(){rm("input.txt");rm("/input.txt");rm("docs");rm("/docs");}
To run:Start up.\ In the current working directoryDestroy ".\input.txt" in the file system.Destroy ".\docs\" in the file system.\ In the filesystem rootDestroy "C:\input.txt" in the file system.Destroy "C:\docs\" in the file system.Shut down.
os.remove("input.txt")os.remove("/input.txt")os.remove("docs")-- must be emptyos.remove("/docs")-- ditto
# possible aliases for Remove-Item: rm, del, riRemove-Iteminput.txtRemove-Item\input.txt# file system rootRemove-Item-Recursedocs# recurse for deleting folders including contentRemove-Item-Recurse\docs
Because input.txt is located inside of "docs" this will delete it when it deletes "docs"
deletedirectory docs
DeleteFile("input.txt")DeleteDirectory("docs","");needstodeleteallincludedfilesDeleteFile("/input.txt")DeleteDirectory("/docs","*.*");deletesallfilesaccordingtoapatternDeleteDirectory("/docs","",#PB_FileSystem_Recursive);deletesallfilesanddirectoriesrecursive
importos# current directoryos.remove("output.txt")os.rmdir("docs")# root directoryos.remove("/output.txt")os.rmdir("/docs")
If you wanted to remove a directory and all its contents, recursively, you would do:
importshutilshutil.rmtree("docs")
file.remove("input.txt")file.remove("/input.txt")# orfile.remove("input.txt","/input.txt")# orunlink("input.txt");unlink("/input.txt")# directories needs the recursive flagunlink("docs",recursive=TRUE)unlink("/docs",recursive=TRUE)
The functionunlink allows wildcards (* and ?)
#langracket;; 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"))
(formerly Perl 6)
unlink'input.txt';unlink'/input.txt';rmdir'docs';rmdir'/docs';
'input.txt' delete'/input.txt' delete'docs' rmdir'/docs' rmdir
; Local.delete%input.txtdelete-dir%docs/; Root.delete%/input.txtdelete-dir%/docs/
'input.txt file:delete'/input.txt file:delete
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. */traceoff/*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. */doj=1for2/*perform this DO loop exactly twice.*/'ERASE'aFile/*erase this file in the current dir. */'RMDIR'"/s /q"aDir/*remove the folder " " " " */ifj==1then'CD \'/*make the current dir the root dir.*/end/* [↑] just do CD \ command once.*//*stick a fork in it, we're all done. */
remove("output.txt")system("rmdir docs")There is a unique RPL instruction to delete both files and directories. Directories must be empty to be deletable.
'output.txt' PURGE'docs' PURGEHOME output.txt' PURGEHOME '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.
File.delete("output.txt","/output.txt")Dir.delete("docs")Dir.delete("/docs")
'------ delete input.txt ----------------kill "input.txt" ' this is where we arekill "/input.txt" ' this is the root' ---- delete directory docs ----------result = rmdir("Docs") ' directory where we areresult = rmdir("/Docs") ' root directoryusestd::io::{self,Write};usestd::fs::{remove_file,remove_dir};usestd::path::Path;usestd::{process,display};constFILE_NAME:&'staticstr="output.txt";constDIR_NAME:&'staticstr="docs";fnmain(){delete(".").and(delete("/")).unwrap_or_else(|e|error_handler(e,1));}fndelete<P>(root:P)->io::Result<()>whereP:AsRef<Path>{remove_file(root.as_ref().join(FILE_NAME)).and(remove_dir(root.as_ref().join(DIR_NAME)))}fnerror_handler<E:fmt::Display>(error:E,code:i32)->!{let_=writeln!(&mutio::stderr(),"{:?}",error);process::exit(code)}
importjava.util._importjava.io.FileobjectFileDeleteTestextendsApp{defdeleteFile(filename:String)={newFile(filename).delete()}deftest(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)}
(delete-filefilename)
The libraryosfiles.s7i provides the functionsremoveFile andremoveTree. 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 exceptionFILE_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;// Delete locally (relative to "the folder")delete file "input.txt"delete folder "docs"// Delete at the file system rootdelete file "/input.txt"delete folder "/docs"
# here%f'input.txt'->delete;%d'docs'->delete;# root dirDir.root+%f'input.txt'->delete;Dir.root+%d'docs'->delete;
(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.
(It will succeed deleting the directory if it is empty)
Fileremove:'input.txt'.Fileremove:'docs'.Fileremove:'/input.txt'.Fileremove:'/docs'
OS.FileSys.remove"input.txt";OS.FileSys.remove"/input.txt";OS.FileSys.rmDir"docs";OS.FileSys.rmDir"/docs";
erase input.txtrmdir docs
filedeleteinput.txt/input.txt#preservedirectoryifnon-emptyfiledeletedocs/docs# delete even if non-emptyfiledelete-forcedocs/docs
needs shell" docs" remove" input.txt" remove
$$ MODE TUSCRIPT- delete fileSET status = DELETE ("input.txt")- delete directorySET status = DELETE ("docs",-std-)&fde "example.txt" # delete&ftr "example.txt" # move to trash
rm -rf docsrm input.txtrm -rf /docsrm /input.txt
decl file ff.delete "input.txt"f.delete "docs"f.delete "/input.txt"f.delete "/docs"
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 .entrymain,0 F3 AF 7F 0066 9 pushaqdesc 00000000'GF 01 FB 0069 10 calls#1, g^lib$do_command;execute shell command 04 0070 11 ret 0071 12 .endmain
Option ExplicitSub DeleteFileOrDirectory()Dim myPath As String myPath = "C:\Users\surname.name\Desktop\Docs"'delete file Kill myPath & "\input.txt"'delete Directory RmDir myPathEnd Sub
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 objectsdim fil, fldset fil = oFSO.GetFile( "input.txt" )fil.Deleteset fld = oFSO.GetFolder( "docs" )fld.Deleteset fil = oFSO.GetFile( "\input.txt" )fil.Deleteset fld = oFSO.GetFolder( "\docs" )fld.Delete
Vedit allows using either '\' or '/' as directory separator character, it is automatically converted to the one used by the operating system.
// In current directoryFile_Delete("input.txt", OK)File_Rmdir("docs")// In the root directoryFile_Delete("/input.txt", OK)File_Rmdir("/docs")Platform:.NET
'Current DirectoryIO.Directory.Delete("docs")IO.Directory.Delete("docs", True) 'also delete files and sub-directoriesIO.File.Delete("output.txt")'RootIO.Directory.Delete("\docs")IO.File.Delete("\output.txt")'Root, platform independentIO.Directory.Delete(IO.Path.DirectorySeparatorChar & "docs")IO.File.Delete(IO.Path.DirectorySeparatorChar & "output.txt")import osfn 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 existsif os.is_file("./input.txt") == true {println("Found file!")}else {println("File was not found!")}// check if directory existsif os.is_dir("./docs") == true {println("Found directory!")}else {println("Directory was not found!")}}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 FileFile.delete("input.txt")// check it workedSystem.print(File.exists("input.txt"))false
;syscall numbers for readability. :]%define sys_rmdir 40%define sys_unlink 10section .textglobal _start_start:mov ebx, fnmov eax, sys_unlinkint 0x80test eax, eaxjs _ragequitmov ebx, dnmov eax, sys_rmdirint 0x80mov ebx, rfnmov eax, sys_unlinkint 0x80cmp eax, 0je _exit_ragequit:mov edx, err_lenmov ecx, err_msgmov ebx, 4mov eax ,1int 0x80_exit:push 0x1mov eax, 1push eaxint 0x80retsection .datafndb 'input.txt',0rfndb '/input.txt',0dndb 'doc',0err_msgdb "Something went wrong! :[",0xaerr_lenequ $-err_msg
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";
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 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")0zkl: System.cmd((System.isWindows and "del" or "unlink") + " /input.txt")unlink: cannot unlink ‘/input.txt’: No such file or directory256zkl: System.cmd("rmdir docs")rmdir: failed to remove ‘docs’: Directory not empty256zkl: System.cmd("rm -r docs")0zkl: System.cmd("rm -r /docs")rm: cannot remove ‘/docs’: No such file or directory256