Check that file exists: Difference between revisions

m (syntax highlighting fixup automation)
 
(24 intermediate revisions by 16 users not shown)
Line 1:
{{task|File System Operations}} [[Category:Simple]]
{{task|File System Operations}}
 
;Task:
Verify that a file called     '''input.txt'''     and   a directory called     '''docs'''     exist.
Line 14:
:::* &nbsp; an unusual filename: &nbsp; <big> ''' `Abdu'l-Bahá.txt ''' </big>
<br><br>
 
=={{header|11l}}==
{{Trans|Python}}
<syntaxhighlight lang="11l">fs:is_file(‘input.txt’)
fs:is_file(‘/input.txt’)
fs:is_dir(‘docs’)
fs:is_dir(‘/docs’)</syntaxhighlight>
 
=={{header|AArch64 Assembly}}==
{{works with|as|Raspberry Pi 3B version Buster 64 bits}}
<syntaxhighlight lang=AArch64"aarch64 Assemblyassembly">
/* ARM assembly AARCH64 Raspberry PI 3B */
/* program verifFic64.s */
Line 137 ⟶ 135:
.include "../includeARM64.inc"
</syntaxhighlight>
 
=={{header|Action!}}==
<syntaxhighlight lang=Action"action!">BYTE lastError
 
PROC MyError(BYTE errCode)
Line 186 ⟶ 183:
File "D:DOS.SYS" exists.
</pre>
 
=={{header|Ada}}==
This example should work with any Ada 95 compiler.
<syntaxhighlight lang="ada">with Ada.Text_IO; use Ada.Text_IO;
 
procedure File_Exists is
Line 207 ⟶ 203:
end File_Exists;</syntaxhighlight>
This example should work with any Ada 2005 compiler.
<syntaxhighlight lang="ada">with Ada.Text_IO; use Ada.Text_IO;
with Ada.Directories; use Ada.Directories;
 
Line 227 ⟶ 223:
Print_Dir_Exist ("/docs");
end File_Exists;</syntaxhighlight>
 
=={{header|Aikido}}==
The <code>stat</code> function returns a <code>System.Stat</code> object for an existing file or directory, or <code>null</code> if it can't be found.
<syntaxhighlight lang="aikido">
function exists (filename) {
return stat (filename) != null
Line 241 ⟶ 236:
 
</syntaxhighlight>
 
=={{header|ALGOL 68}}==
{{works with|ALGOL 68G|Any - tested with release 2.8.3.win32}}
Uses the Algol 68G specific "file is directory" procedure to test for the existence of directories.
<syntaxhighlight lang="algol68"># Check files and directories exist #
 
# check a file exists by attempting to open it for input #
Line 285 ⟶ 279:
test directory exists( "docs" );
test directory exists( "\docs" )</syntaxhighlight>
 
=={{header|Amazing Hopper}}==
Version: hopper-FLOW!:
<syntaxhighlight lang=Amazing"amazing Hopperhopper">
#include <flow.h>
 
Line 317 ⟶ 310:
$
</pre>
 
=={{header|APL}}==
<syntaxhighlight lang="apl">
h ← ⎕fio['fopen'] 'input.txt'
h
Line 338 ⟶ 330:
¯1
</syntaxhighlight>
 
=={{header|AppleScript}}==
{{Trans|JavaScript}}
(macOS JavaScript for Automation)
<syntaxhighlight lang=AppleScript"applescript">use framework "Foundation" -- YOSEMITE OS X onwards
use scripting additions
 
Line 440 ⟶ 431:
The last four are returned by `doesDirectoryExist`,
which yields false for simple files, and true for directories.
<syntaxhighlight lang=AppleScript"applescript">{true, true, true, true, false, false, true, true}</syntaxhighlight>
 
=={{header|Applesoft BASIC}}==
The error code for FILE NOT FOUND is 6.
<syntaxhighlight lang=ApplesoftBasic"applesoftbasic">100 F$ = "THAT FILE"
110 T$(0) = "DOES NOT EXIST."
120 T$(1) = "EXISTS."
Line 466 ⟶ 456:
360 RETURN
</syntaxhighlight>
 
=={{header|ARM Assembly}}==
{{works with|as|Raspberry Pi}}
<syntaxhighlight lang=ARM"arm Assemblyassembly">
/* ARM assembly Raspberry PI */
/* program verifFic.s */
Line 594 ⟶ 583:
bx lr /* return */
</syntaxhighlight>
 
=={{header|Arturo}}==
<syntaxhighlight lang="rebol">checkIfExists: function [fpath][
(or? exists? fpath
exists? .directory fpath)? -> print [fpath "exists"]
Line 607 ⟶ 595:
checkIfExists "/input.txt"
checkIfExists "/docs"</syntaxhighlight>
 
=={{header|AutoHotkey}}==
AutoHotkey’s FileExist() function returns an attribute string (a subset of "RASHNDOCT") if a matching file or directory is found. The attribute string must be parsed for the letter D to determine whether the match is a directory or file.
Line 613 ⟶ 600:
Another option is AutoHotkey's IfExist/IfNotExist command
 
<syntaxhighlight lang="autohotkey">; FileExist() function examples
ShowFileExist("input.txt")
ShowFileExist("\input.txt")
Line 646 ⟶ 633:
Return
}</syntaxhighlight>
 
=={{header|AWK}}==
{{works with|gawk}}
<syntaxhighlight lang="awk">@load "filefuncs"
 
function exists(name ,fd) {
Line 665 ⟶ 651:
 
Portable getline method. Also works in a Windows environment.
<syntaxhighlight lang=AWK"awk">#
# Check if file or directory exists, even 0-length file.
# Return 0 if not exist, 1 if exist
Line 693 ⟶ 679:
{{works with|gawk}}
Check file(s) existence
<syntaxhighlight lang="text">gawk 'BEGINFILE{if (ERRNO) {print "Not exist."; nextfile} else {print "Exist."; nextfile}}' input.txt input-missing.txt</syntaxhighlight>
 
=={{header|Axe}}==
<syntaxhighlight lang="axe">If GetCalc("appvINPUT")
Disp "EXISTS",i
Else
Disp "DOES NOT EXIST",i
End</syntaxhighlight>
 
=={{header|BASIC}}==
{{works with|QBasic}}
<syntaxhighlight lang="qbasic">
ON ERROR GOTO ohNo
f$ = "input.txt"
Line 737 ⟶ 721:
You can also check for a directory by trying to enter it.
 
<syntaxhighlight lang="qbasic">
ON ERROR GOTO ohNo
d$ = "docs"
Line 758 ⟶ 742:
Later versions of MS-compatible BASICs include the <CODE>DIR$</CODE> keyword, which makes this pretty trivial.
 
<syntaxhighlight lang="qbasic">
f$ = "input.txt"
GOSUB opener
Line 783 ⟶ 767:
 
==={{header|BaCon}}===
<syntaxhighlight lang="freebasic">' File exists
f$ = "input.txt"
d$ = "docs"
Line 810 ⟶ 794:
==={{header|Commodore BASIC}}===
Try a file, then check the error status of the disk drive. Error code 62 is the "File not found" error. The trick is to open the file without specifying the file type (PRG, SEQ, REL, etc.) and the Read/Write mode in the OPEN statement, otherwise you may end up with error code 64 "File Type Mismatch".
<syntaxhighlight lang="gwbasic">10 REM CHECK FILE EXISTS
15 ER=0:EM$="":MSG$="FILE EXISTS."
20 PRINT CHR$(147);:REM CLEAR SCREEN
Line 837 ⟶ 821:
ENTER FILENAME TO CHECK? NOFILE.DOC
'NOFILE.DOC' IS NOT HERE.</pre>
 
==={{header|SmallBASIC}}===
<syntaxhighlight lang="qbasic">
if(isdir("docs")) then print "directory docs exist"
if(isdir("/docs")) then print "directory /docs exist"
if(isfile("input.txt")) then print "file input.txt exist"
if(isfile("/input.txt")) then print "file /input.txt exist"
</syntaxhighlight>
 
 
 
=={{header|BASIC256}}==
<syntaxhighlight lang=BASIC256"basic256">subroutine opener (filename$)
if exists(filename$) then
print filename$; " exists"
Line 854 ⟶ 848:
call opener ("`Abdu'l-Bahá.txt"))
end</syntaxhighlight>
 
=={{header|Batch File}}==
<syntaxhighlight lang="dos">if exist input.txt echo The following file called input.txt exists.
if exist \input.txt echo The following file called \input.txt exists.
if exist docs echo The following directory called docs exists.
if exist \docs\ echo The following directory called \docs\ exists.</syntaxhighlight>
 
=={{header|BBC BASIC}}==
<syntaxhighlight lang="bbcbasic"> test% = OPENIN("input.txt")
IF test% THEN
CLOSE #test%
Line 885 ⟶ 877:
PRINT "Directory \docs exists"
ENDIF</syntaxhighlight>
 
=={{header|BQN}}==
 
Line 892 ⟶ 883:
Takes filename as a command line argument, tells whether it exists.
 
<syntaxhighlight lang=BQN"bqn">fname ← ⊑args
•Out fname∾" Does not exist"‿" Exists"⊑˜•File.exists fname</syntaxhighlight>
 
=={{header|C}}==
{{libheader|POSIX}}
<syntaxhighlight lang="c">#include <sys/types.h>
#include <sys/stat.h>
#include <stdio.h>
Line 925 ⟶ 915:
return 0;
}</syntaxhighlight>
 
{{libheader|Gadget}}
<syntaxhighlight lang="c">
#include <gadget/gadget.h>
 
LIB_GADGET_START
 
/* input.txt = check_file.c
docs = tests */
 
Main
Print "tests/check_file.c is a regular file? %s\n", Exist_file("tests/check_file.c") ? "yes" : "no";
Print "tests is a directory? %s\n", Exist_dir("tests") ? "yes" : "no";
Print "some.txt is a regular file? %s\n", Exist_file("some.txt") ? "yes" : "no";
Print "/tests is a directory? %s\n", Exist_dir("/tests") ? "yes" : "no";
End
</syntaxhighlight>
{{out}}
<pre>
tests/check_file.c is a regular file? yes
tests is a directory? yes
some.txt is a regular file? no
/tests is a directory? no
 
</pre>
 
=={{header|C sharp|C#}}==
 
<syntaxhighlight lang="csharp">using System.IO;
 
Console.WriteLine(File.Exists("input.txt"));
Line 934 ⟶ 949:
Console.WriteLine(Directory.Exists("docs"));
Console.WriteLine(Directory.Exists("/docs"));</syntaxhighlight>
 
=={{header|C++}}==
{{libheader|boost}}
<syntaxhighlight lang="cpp">#include "boost/filesystem.hpp"
#include <string>
#include <iostream>
Line 962 ⟶ 976:
testfile("/docs");
}</syntaxhighlight>
 
===Using C++ 17===
C++ 17 contains a Filesystem library which significantly improves operations with files.
<syntaxhighlight lang="c++">
 
#include <iostream>
#include <filesystem>
 
void file_exists(const std::filesystem::path& path) {
std::cout << path;
if ( std::filesystem::exists(path) ) {
if ( std::filesystem::is_directory(path) ) {
std::cout << " is a directory" << std::endl;
} else {
std::cout << " exists with a file size of " << std::filesystem::file_size(path) << " bytes." << std::endl;
}
} else {
std::cout << " does not exist" << std::endl;
}
}
 
int main() {
file_exists("input.txt");
file_exists("zero_length.txt");
file_exists("docs/input.txt");
file_exists("docs/zero_length.txt");
}
</syntaxhighlight>
{{ out }}
</pre>
"input.txt" exists with a file size of 11 bytes.
 
"zero_length.txt" exists with a file size of 0 bytes.
 
"docs/input.txt" exists with a file size of 11 bytes.
 
"docs/zero_length.txt" exists with a file size of 0 bytes.
</pre>
 
=={{header|Clojure}}==
<syntaxhighlight lang="clojure">
 
(dorun (map #(.exists (clojure.java.io/as-file %)) '("/input.txt" "/docs" "./input.txt" "./docs")))
 
</syntaxhighlight>
 
=={{header|COBOL}}==
{{works with|GnuCOBOL}} and other compilers with this system call extension
<syntaxhighlight lang=COBOL"cobol"> identification division.
program-id. check-file-exist.
 
Line 1,059 ⟶ 1,110:
error: CBL_CHECK_FILE_EXIST +000000035 /docs/</pre>
Errors due to file and dir not existing in root directory for this test pass
 
=={{header|CoffeeScript}}==
{{works with|Node.js}}
<syntaxhighlight lang="coffeescript">
fs = require 'fs'
path = require 'path'
Line 1,086 ⟶ 1,136:
 
</syntaxhighlight>
 
=={{header|Common Lisp}}==
 
''probe-file'' returns ''nil'' if a file does not exist. ''directory'' returns ''nil'' if there are no files in a specified directory.
<syntaxhighlight lang="lisp">(if (probe-file (make-pathname :name "input.txt"))
(print "rel file exists"))
(if (probe-file (make-pathname :directory '(:absolute "") :name "input.txt"))
Line 1,105 ⟶ 1,154:
 
{{libheader|CL-FAD}}
<syntaxhighlight lang="lisp">(if (cl-fad:directory-exists-p (make-pathname :directory '(:relative "docs")))
(print "rel directory exists")
(print "rel directory does not exist"))</syntaxhighlight>
 
=={{header|Crystal}}==
<syntaxhighlight lang="ruby">def check_file(filename : String)
if File.directory?(filename)
puts "#{filename} is a directory"
Line 1,124 ⟶ 1,172:
check_file("/input.txt")
check_file("/docs")</syntaxhighlight>
 
=={{header|D}}==
<syntaxhighlight lang="d">import std.stdio, std.file, std.path;
 
void verify(in string name) {
Line 1,149 ⟶ 1,196:
'\input.txt' doesn't exist
'\docs' doesn't exist</pre>
 
=={{header|DBL}}==
<syntaxhighlight lang=DBL"dbl">;
; Check file and directory exists for DBL version 4 by Dario B.
;
Line 1,186 ⟶ 1,232:
CLOSE 2
STOP</syntaxhighlight>
 
=={{header|DCL}}==
<syntaxhighlight lang=DCL"dcl">$ if f$search( "input.txt" ) .eqs. ""
$ then
$ write sys$output "input.txt not found"
Line 1,219 ⟶ 1,264:
[000000]input.txt not found
directory [000000]docs not found</pre>
 
=={{header|Delphi}}==
<syntaxhighlight lang=Delphi"delphi">program EnsureFileExists;
 
{$APPTYPE CONSOLE}
Line 1,249 ⟶ 1,293:
Writeln('Directory "\docs" does not exists.');
end.</syntaxhighlight>
 
=={{header|E}}==
<syntaxhighlight lang="e">for file in [<file:input.txt>,
<file:///input.txt>] {
require(file.exists(), fn { `$file is missing!` })
Line 1,262 ⟶ 1,305:
require(file.isDirectory(), fn { `$file is not a directory!` })
}</syntaxhighlight>
 
=={{header|Elena}}==
ELENA 4.x :
<syntaxhighlight lang="elena">import system'io;
import extensions;
 
Line 1,284 ⟶ 1,326:
console.printLine("\docs directory ",Directory.assign("\docs").validatePath())
}</syntaxhighlight>
 
=={{header|Elixir}}==
<syntaxhighlight lang=Elixir"elixir">File.regular?("input.txt")
File.dir?("docs")
File.regular?("/input.txt")
File.dir?("/docs")</syntaxhighlight>
 
=={{header|Emacs Lisp}}==
<syntaxhighlight lang=Lisp"lisp">(file-exists-p "input.txt")
(file-directory-p "docs")
(file-exists-p "/input.txt")
Line 1,298 ⟶ 1,338:
 
<code>file-exists-p</code> is true on both files and directories. <code>file-directory-p</code> is true only on directories. Both go through the <code>file-name-handler-alist</code> "magic filenames" mechanism so can act on remote files. On MS-DOS generally both <code>/</code> and <code>\</code> work to specify the root directory.
 
=={{header|Erlang}}==
<syntaxhighlight lang="erlang">#!/usr/bin/escript
existence( true ) ->"exists";
existence( false ) ->"does not exist".
Line 1,313 ⟶ 1,352:
print_result( "Directory", "/docs", filelib:is_dir("/docs") ).
</syntaxhighlight>
 
=={{header|Euphoria}}==
<syntaxhighlight lang="euphoria">include file.e
 
procedure ensure_exists(sequence name)
Line 1,337 ⟶ 1,375:
ensure_exists("/input.txt")
ensure_exists("/docs")</syntaxhighlight>
 
=={{header|F_Sharp|F#}}==
<syntaxhighlight lang="fsharp">open System.IO
File.Exists("input.txt")
Directory.Exists("docs")
File.Exists("/input.txt")
Directory.Exists(@"\docs")</syntaxhighlight>
 
=={{header|Factor}}==
<syntaxhighlight lang="factor">: print-exists? ( path -- )
[ write ": " write ] [ exists? "exists." "doesn't exist." ? print ] bi ;
 
{ "input.txt" "/input.txt" "docs" "/docs" } [ print-exists? ] each</syntaxhighlight>
 
=={{header|Forth}}==
 
<syntaxhighlight lang="forth">: .exists ( str len -- ) 2dup file-status nip 0= if ." exists" else ." does not exist" then type ;
2dup file-status nip 0= if
s" input.txt" .exists
s" /input .txt" .exists: "
else
s" docs" .exists
." does not exist: "
s" /docs" .exists</syntaxhighlight>
then
type
;
 
s" input.txt" .exists cr
s" /input.txt" .exists cr
s" docs" .exists cr
s" /docs" .exists cr
</syntaxhighlight>
 
=={{header|Fortran}}==
Line 1,363 ⟶ 1,407:
 
Cannot check for directories in Fortran
<syntaxhighlight lang="fortran">LOGICAL :: file_exists
INQUIRE(FILE="input.txt", EXIST=file_exists) ! file_exists will be TRUE if the file
! exists and FALSE otherwise
Line 1,370 ⟶ 1,414:
Actually, f90,f95 are able to deal with directory staff:
 
<syntaxhighlight lang="fortran">logical :: dir_e
! a trick to be sure docs is a dir
inquire( file="./docs/.", exist=dir_e )
Line 1,379 ⟶ 1,423:
call system('mkdir docs')
end if</syntaxhighlight>
 
=={{header|FreeBASIC}}==
<syntaxhighlight lang="freebasic">' FB 1.05.0 Win64
 
' Enable FileExists() function to be used
Line 1,428 ⟶ 1,471:
'c:\docs' exists
</pre>
 
 
 
=={{header|Frink}}==
This checks that the file exists and is a file, and that the directory exists, and is a directory. (Many of the samples on this page do not check that the files are actually a file or the directories are actually a directory.) It also tries to find various Unicode encodings of the "unusual" filename that may be encoded in different Unicode compositions (e.g. using "precomposed" or "decomposed" representations for some characters.
 
<syntaxhighlight lang="frink">
checkFile[filename] :=
{
Line 1,467 ⟶ 1,512:
checkFile[normalizeUnicode[unusual, "NFC"]]
checkFile[normalizeUnicode[unusual, "NFD"]]
</syntaxhighlight>
 
 
=={{header|FutureBasic}}==
<syntaxhighlight lang="futurebasic">
include "NSLog.incl"
 
CFURLRef url
url = fn URLFileURLWithPath( fn StringByExpandingTildeInPath(@"~/Desktop/input.txt") )
if (fn FileManagerFileExistsAtURL( url ) )
NSLog( @"File \"input.txt\" exists." )
else
NSLog( @"File \"input.txt\" does not exist at this location." )
end if
 
url = fn URLFileURLWithPath( fn StringByExpandingTildeInPath(@"~/Desktop/docs") )
if (fn FileManagerIsDirectoryAtURL( url ) )
NSLog( @"Directory \"docs\" exists." )
else
NSLog( @"Directory \"docs\" does not exist at this location." )
end if
 
HandleEvents
</syntaxhighlight>
 
=={{header|Gambas}}==
'''[https://gambas-playground.proko.eu/?gist=fa06b7cc43166fb0ab48e878d86e3d1b Click this link to run this code]'''
<syntaxhighlight lang="gambas">Public Sub Main()
 
If Exist(User.Home &/ "input.txt") Then Print "'input.txt' does exist in the Home folder"
Line 1,491 ⟶ 1,559:
'`Abdu'l-Bahá.txt' does exist (zero length and unusual name)
</pre>
 
 
 
=={{header|GAP}}==
<syntaxhighlight lang="gap">IsExistingFile("input.txt");
IsDirectoryPath("docs");
IsExistingFile("/input.txt");
IsDirectoryPath("/docs");</syntaxhighlight>
 
=={{header|Genie}}==
<syntaxhighlight lang="genie">[indent=4]
/*
Check file exists, in Genie
Line 1,528 ⟶ 1,597:
 
For the run, ''input.txt'' was zero length.
 
=={{header|Go}}==
<syntaxhighlight lang="go">package main
 
import (
Line 1,554 ⟶ 1,622:
printStat("/docs")
}</syntaxhighlight>
 
=={{header|Groovy}}==
<syntaxhighlight lang="groovy">println new File('input.txt').exists()
println new File('/input.txt').exists()
println new File('docs').exists()
println new File('/docs').exists()</syntaxhighlight>
 
=={{header|Haskell}}==
 
<syntaxhighlight lang="haskell">import System.Directory (doesFileExist, doesDirectoryExist)
 
check :: (FilePath -> IO Bool) -> FilePath -> IO ()
Line 1,580 ⟶ 1,646:
check doesFileExist "/input.txt"
check doesDirectoryExist "/docs"</syntaxhighlight>
 
=={{header|hexiscript}}==
<syntaxhighlight lang="hexiscript">println "File \"input.txt\"? " + (exists "input.txt")
println "Dir \"docs\"? " + (exists "docs/")
println "File \"/input.txt\"? " + (exists "/input.txt")
println "Dir \"/docs\"? " + (exists "/docs/")</syntaxhighlight>
 
=={{header|HicEst}}==
<syntaxhighlight lang="hicest"> OPEN(FIle= 'input.txt', OLD, IOStat=ios, ERror=99)
OPEN(FIle='C:\input.txt', OLD, IOStat=ios, ERror=99)
! ...
99 WRITE(Messagebox='!') 'File does not exist. Error message ', ios </syntaxhighlight>
 
=={{header|HolyC}}==
<syntaxhighlight lang="holyc">U0 FileExists(U8 *f) {
if (FileFind(f) && !IsDir(f)) {
Print("'%s' file exists.\n", f);
Line 1,614 ⟶ 1,677:
DirExists("docs");
DirExists("::/docs");</syntaxhighlight>
 
=={{header|i}}==
<syntaxhighlight lang="i">concept exists(path) {
open(path)
errors {
Line 1,634 ⟶ 1,696:
exists("docs/Abdu'l-Bahá.txt")
}</syntaxhighlight>
 
=={{header|Icon}} and {{header|Unicon}}==
Icon doesn't support 'stat'; however, information can be obtained by use of the system function to access command line.
<syntaxhighlight lang=Unicon"unicon">every dir := !["./","/"] do {
write("file ", f := dir || "input.txt", if stat(f) then " exists." else " doesn't exist.")
write("directory ", f := dir || "docs", if stat(f) then " exists." else " doesn't exist.")
}</syntaxhighlight>
Note: Icon and Unicon accept both / and \ for directory separators.
 
=={{header|IDL}}==
<syntaxhighlight lang="idl">
print, FILE_TEST('input.txt')
print, FILE_TEST(PATH_SEP()+'input.txt')
Line 1,651 ⟶ 1,711:
 
</syntaxhighlight>
 
=={{header|J}}==
<syntaxhighlight lang="j">require 'files'
fexist 'input.txt'
fexist '/input.txt'
Line 1,659 ⟶ 1,718:
direxist 'docs'
direxist '/docs'</syntaxhighlight>
 
=={{header|Java}}==
This can be done with a <code>File</code> object.<br />
<syntaxhighlight lang=java>import java.io.File;
<syntaxhighlight lang="java">
new File("docs/input.txt").exists();
new File("/docs/input.txt").exists();
</syntaxhighlight>
Zero-length files are not a problem, and return as existent.<br />
Java supports UTF-16, so the unusual file name is not a problem.
<syntaxhighlight lang="java">
new File("`Abdu'l-Bahá.txt").exists()
</syntaxhighlight>
<syntaxhighlight lang="java">
new File("`Abdu'l-Bah\u00E1.txt").exists();
</syntaxhighlight>
<br />
Alternately
<syntaxhighlight lang="java">import java.io.File;
public class FileExistsTest {
public static boolean isFileExists(String filename) {
Line 1,680 ⟶ 1,753:
}</syntaxhighlight>
{{works with|Java|7+}}
<syntaxhighlight lang="java5">import java.nio.file.FileSystem;
import java.nio.file.FileSystems;
import java.nio.file.Files;
Line 1,705 ⟶ 1,778:
Each non-browser JS context is likely to have its own home-grown and unstandardised file system library.
===JScript===
<syntaxhighlight lang="javascript">var fso = new ActiveXObject("Scripting.FileSystemObject");
 
fso.FileExists('input.txt');
Line 1,716 ⟶ 1,789:
{{Trans|Haskell}}
(Adopting function names used in the Haskell System.Directory library)
<syntaxhighlight lang=JavaScript"javascript">(() => {
 
// SYSTEM DIRECTORY FUNCTIONS
Line 1,804 ⟶ 1,877:
true
]</pre>
 
=={{header|Julia}}==
{{works with|Julia|0.6}}
 
<syntaxhighlight lang="julia">@show isfile("input.txt")
@show isfile("/input.txt")
@show isdir("docs")
Line 1,814 ⟶ 1,886:
@show isfile("")
@show isfile("`Abdu'l-Bahá.txt")</syntaxhighlight>
 
=={{header|Klingphix}}==
<syntaxhighlight lang=Klingphix"klingphix">include ..\Utilitys.tlhy
 
"foo.bar" "w" fopen
Line 1,828 ⟶ 1,899:
{{out}}
<pre>Could not open 'fou.bar' for reading</pre>
 
=={{header|Kotlin}}==
<syntaxhighlight lang="scala">// version 1.0.6
 
import java.io.File
Line 1,846 ⟶ 1,916:
}
}</syntaxhighlight>
 
=={{header|LabVIEW}}==
{{libheader|LabVIEW CWD}}
{{VI snippet}}<br/>
[[File:Ensure_that_a_file_exists.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.existsFile($file1)
[[io]]::fp.closeFile($file1)
 
$file2 = [[io]]::fp.openFile(/input.txt)
[[io]]::fp.existsFile($file2)
[[io]]::fp.closeFile($file2)
 
$dir1 = [[io]]::fp.openFile(docs)
[[io]]::fp.existsFile($dir1)
[[io]]::fp.closeFile($dir1)
 
$dir2 = [[io]]::fp.openFile(/docs)
[[io]]::fp.existsFile($dir2)
[[io]]::fp.closeFile($dir2)
</syntaxhighlight>
 
=={{header|langur}}==
The prop() function returns a hash of file/directory properties.
<syntaxhighlight lang="langur">val .printresult = impure fn(.file) {
write .file, ": "
if val .p = prop(.file) {
if .p'isdir {
writeln "is directory"
} else {
writeln "is file"
}
} else {
writeln "nothing"
}
}
 
.printresult("input.txt")
.printresult("/input.txt")
.printresult("docs")
.printresult("/docs")
</syntaxhighlight>
 
=={{header|Lasso}}==
<syntaxhighlight lang=Lasso"lasso">// local file
file_exists('input.txt')
 
Line 1,864 ⟶ 1,979:
// directory in root file system (requires permissions at user OS level)
file_exists('//docs')</syntaxhighlight>
 
=={{header|LFE}}==
From the LFE REPL:
<syntaxhighlight lang="lisp">
> (: filelib is_regular '"input.txt")
false
Line 1,877 ⟶ 1,991:
false
</syntaxhighlight>
 
=={{header|Liberty BASIC}}==
<syntaxhighlight lang="lb">'fileExists.bas - Show how to determine if a file exists
dim info$(10,10)
input "Type a file path (ie. c:\windows\somefile.txt)?"; fpath$
Line 1,908 ⟶ 2,021:
filenameOnly$ = right$(fullPath$, len(fullPath$)-pathLength)
end function</syntaxhighlight>
 
=={{header|Little}}==
<syntaxhighlight lang=C"c">if (exists("input.txt")) {
puts("The file \"input.txt\" exist");
}
Line 1,922 ⟶ 2,034:
puts("The file \"/docs\" exist");
}</syntaxhighlight>
 
=={{header|LiveCode}}==
<syntaxhighlight lang=LiveCode"livecode">there is a file "/input.txt"
there is a file "input.txt"
there is a folder "docs"
there is a file "/docs/input.txt"</syntaxhighlight>
LiveCode also allows setting a default folder for subsequent file commands. To check if a file exists in the doc folder
<syntaxhighlight lang=LiveCode"livecode">set the defaultFolder to "docs"
there is a file "input.txt"</syntaxhighlight>
 
=={{header|Logo}}==
{{works with|UCB Logo}}
<syntaxhighlight lang="logo">show file? "input.txt
show file? "/input.txt
show file? "docs
show file? "/docs</syntaxhighlight>
Alternatively, one can set a file prefix used for subsequent file commands.
<syntaxhighlight lang="logo">setprefix "/
show file? "input.txt</syntaxhighlight>
 
=={{header|Lua}}==
For directories, the following only works on platforms on which directories can be opened for reading like files.
<syntaxhighlight lang="lua">function output( s, b )
if b then
print ( s, " does not exist." )
Line 1,958 ⟶ 2,067:
 
The following more portable solution uses LuaFileSystem.
<syntaxhighlight lang="lua">require "lfs"
for i, path in ipairs({"input.txt", "/input.txt", "docs", "/docs"}) do
local mode = lfs.attributes(path, "mode")
Line 1,967 ⟶ 2,076:
end
end</syntaxhighlight>
 
=={{header|M2000 Interpreter}}==
Report print proportional text using word wrap, and justification. Can be used to calculate lines, and to render form a line, a number of lines. We can specify the width of the text, and by moving the cursor horizontal we can specify the left margin. This statement can be used to any layer, including user forms and printer page.
 
<syntaxhighlight lang=M2000"m2000 Interpreterinterpreter">
Module ExistDirAndFile {
Let WorkingDir$=Dir$, RootDir$="C:\"
Line 1,991 ⟶ 2,099:
ExistDirAndFile
</syntaxhighlight>
 
=={{header|Maple}}==
<syntaxhighlight lang=Maple"maple">with(FileTools):
Exists("input.txt");
Exists("docs") and IsDirectory("docs");
Exists("/input.txt");
Exists("/docs") and IsDirectory("/docs");</syntaxhighlight>
 
=={{header|Mathematica}} / {{header|Wolfram Language}}==
<syntaxhighlight lang=Mathematica"mathematica">wd = NotebookDirectory[];
FileExistsQ[wd <> "input.txt"]
DirectoryQ[wd <> "docs"]
Line 2,006 ⟶ 2,112:
FileExistsQ["/" <> "input.txt"]
DirectoryQ["/" <> "docs"]</syntaxhighlight>
 
=={{header|MATLAB}} / {{header|Octave}}==
<syntaxhighlight lang=Matlab"matlab"> exist('input.txt','file')
exist('/input.txt','file')
exist('docs','dir')
exist('/docs','dir')</syntaxhighlight>
 
=={{header|MAXScript}}==
<syntaxhighlight lang="maxscript">-- Here
doesFileExist "input.txt"
(getDirectories "docs").count == 1
Line 2,020 ⟶ 2,124:
doesFileExist "\input.txt"
(getDirectories "C:\docs").count == 1</syntaxhighlight>
 
=={{header|Modula-3}}==
<syntaxhighlight lang="modula3">MODULE FileTest EXPORTS Main;
 
IMPORT IO, Fmt, FS, File, OSError, Pathname;
Line 2,043 ⟶ 2,146:
IO.Put(Fmt.Bool(FileExists("/docs")) & "\n");
END FileTest.</syntaxhighlight>
 
=={{header|Nanoquery}}==
<syntaxhighlight lang=Nanoquery"nanoquery">import Nanoquery.IO
 
def exists(fname)
Line 2,052 ⟶ 2,154:
return f.exists()
end</syntaxhighlight>
 
=={{header|Neko}}==
<syntaxhighlight lang=ActionScript"actionscript">/**
Check that file/dir exists, in Neko
*/
Line 2,091 ⟶ 2,192:
empty.txt exists as empty file: true
`Abdu'l-Bahá.txt exists as file: true</pre>
 
=={{header|Nemerle}}==
{{trans|C#}}
<syntaxhighlight lang=Nemerle"nemerle">using System.Console;
using System.IO;
Line 2,101 ⟶ 2,201:
WriteLine(Directory.Exists("docs"));
WriteLine(Directory.Exists("/docs"));</syntaxhighlight>
 
=={{header|NetRexx}}==
<syntaxhighlight lang=NetRexx"netrexx">/* NetRexx */
options replace format comments java crossref symbols binary
 
Line 2,148 ⟶ 2,247:
return
</syntaxhighlight>
 
=={{header|NewLISP}}==
<syntaxhighlight lang=NewLISP"newlisp">(dolist (file '("input.txt" "/input.txt"))
(if (file? file true)
(println "file " file " exists")))
Line 2,157 ⟶ 2,255:
(if (directory? dir)
(println "directory " dir " exists")))</syntaxhighlight>
 
=={{header|Nim}}==
<syntaxhighlight lang="nim">import os
 
echo fileExists "input.txt"
Line 2,165 ⟶ 2,262:
echo dirExists "docs"
echo dirExists "/docs"</syntaxhighlight>
 
=={{header|Objeck}}==
<syntaxhighlight lang="objeck">
use IO;
 
Line 2,182 ⟶ 2,278:
 
=={{header|Objective-C}}==
<syntaxhighlight lang="objc">NSFileManager *fm = [NSFileManager defaultManager];
NSLog(@"input.txt %s", [fm fileExistsAtPath:@"input.txt"] ? @"exists" : @"doesn't exist");
NSLog(@"docs %s", [fm fileExistsAtPath:@"docs"] ? @"exists" : @"doesn't exist");</syntaxhighlight>
 
=={{header|Odin}}==
 
<syntaxhighlight lang="odin">package main
 
import "core:os"
 
main :: proc() {
os.exists("input.txt")
os.exists("/input.txt")
os.exists("docs")
os.exists("/docs")
}</syntaxhighlight>
 
=={{header|OCaml}}==
<syntaxhighlight lang="ocaml">Sys.file_exists "input.txt";;
Sys.file_exists "docs";;
Sys.file_exists "/input.txt";;
Sys.file_exists "/docs";;</syntaxhighlight>
 
=={{header|ooRexx}}==
<syntaxhighlight lang="oorexx">/**********************************************************************
* exists(filespec)
* returns 1 if filespec identifies a file with size>0
Line 2,213 ⟶ 2,321:
If size=0 Then Say spec 'is a zero-size file'
Return 0</syntaxhighlight>
 
=={{header|Oz}}==
<syntaxhighlight lang="oz">declare
[Path] = {Module.link ['x-oz://system/os/Path.ozf']}
in
Line 2,222 ⟶ 2,329:
{Show {Path.exists "/docs"}}
{Show {Path.exists "/input.txt"}}</syntaxhighlight>
 
=={{header|PARI/GP}}==
<syntaxhighlight lang="parigp">trap(,"does not exist",read("input.txt");"exists")
trap(,"does not exist",read("c:\\input.txt");"exists")
trap(,"does not exist",read("c:\\dirname\\nul");"exists")</syntaxhighlight>
Line 2,231 ⟶ 2,337:
 
Under PARI it would typically be more convenient to use [[#C|C]] methods.
 
=={{header|Pascal}}==
See [[Ensure_that_a_file_exists#Delphi | Delphi]]
 
=={{header|Perl}}==
<syntaxhighlight lang="perl">use File::Spec::Functions qw(catfile rootdir);
# here
print -e 'input.txt';
Line 2,251 ⟶ 2,355:
perl -e 'print -e "/input.txt", "\n";'
perl -e 'print -d "/docs", "\n";'
 
=={{header|Phix}}==
{{libheader|Phix/basics}}
<!--<syntaxhighlight lang=Phix"phix">(notonline)-->
<span style="color: #008080;">without</span> <span style="color: #008080;">js</span> <span style="color: #000080;font-style:italic;">-- (file i/o)</span>
<span style="color: #008080;">procedure</span> <span style="color: #000000;">check</span><span style="color: #0000FF;">(</span><span style="color: #004080;">string</span> <span style="color: #000000;">name</span><span style="color: #0000FF;">)</span>
Line 2,280 ⟶ 2,383:
directory /Program Files (x86) exists.
</pre>
 
=={{header|Phixmonti}}==
<syntaxhighlight lang=Phixmonti"phixmonti">"foo.bar" "w" fopen
"Hallo !" over fputs
fclose
Line 2,288 ⟶ 2,390:
"fou.bar" "r" fopen
dup 0 < if "Could not open 'foo.bar' for reading" print drop else fclose endif</syntaxhighlight>
 
=={{header|PHP}}==
<syntaxhighlight lang="php">if (file_exists('input.txt')) echo 'input.txt is here right by my side';
if (file_exists('docs' )) echo 'docs is here with me';
if (file_exists('/input.txt')) echo 'input.txt is over there in the root dir';
if (file_exists('/docs' )) echo 'docs is over there in the root dir';</syntaxhighlight>
 
=={{header|PicoLisp}}==
<syntaxhighlight lang=PicoLisp"picolisp">(if (info "file.txt")
(prinl "Size: " (car @) " bytes, last modified " (stamp (cadr @) (cddr @)))
(prinl "File doesn't exist") )
Line 2,317 ⟶ 2,417:
(NIL "Directory exists") ) ) )
</syntaxhighlight>
 
=={{header|Pike}}==
<syntaxhighlight lang="pike">import Stdio;
 
int main(){
Line 2,330 ⟶ 2,429:
}
}</syntaxhighlight>
 
=={{header|PL/I}}==
<syntaxhighlight lang="pli">*Process source or(!);
/*********************************************************************
* 20.10.2013 Walter Pachl
Line 2,359 ⟶ 2,457:
File D:\_l\nix.txt not found
</pre>
 
=={{header|PL/M}}==
This sample assumes that the original 8080 PL/M compiler is used and that the program will be running under CP/M.
Line 2,365 ⟶ 2,462:
<br>Note that CP/M restricts file names to 7-bit ascii upper-case and not all non-letter, non-digit characters can be used.
<br>CP/M filenames are up to 8 characters long with an optional, up to three character extension.
<syntaxhighlight lang="plm">100H:
 
DECLARE FCB$SIZE LITERALLY '36';
Line 2,461 ⟶ 2,558:
Bdos Err on A: Select
</pre>
 
=={{header|Plain English}}==
{{libheader|Plain English-output}}
<syntaxhighlight lang="text">
To run:
Start up.
\ In the current working directory
Check that ".\input.txt" is in the file system.
Check that ".\docs\" is in the file system.
\ In the filesystem root
Check that "C:\input.txt" is in the file system.
Check that "C:\docs\" is in the file system.
Wait for the escape key.
Shut down.
 
To check that a path is in the file system:
If the path is in the file system, write the path then " exists" to the output; exit.
If the path is not in the file system, write the path then " does not exist" to the output; exit.
</syntaxhighlight>
 
=={{header|Pop11}}==
 
<syntaxhighlight lang="pop11">sys_file_exists('input.txt') =>
sys_file_exists('/input.txt') =>
sys_file_exists('docs') =>
Line 2,473 ⟶ 2,589:
The only sure method to check if file can be read is to try to open it. If one just wants to check if file is readable the following may be useful:
 
<syntaxhighlight lang="pop11">;;; Define an auxilary function, returns boolean
define file_readable(fname);
lvars f = sysopen(fname, 0, true, `A`);
Line 2,494 ⟶ 2,610:
 
Users can easily define special cases of the general procedure.
 
=={{header|PowerShell}}==
 
<syntaxhighlight lang="powershell"> if (Test-Path -Path .\input.txt) {
write-host "File input exist"
}
Line 2,503 ⟶ 2,618:
write-host "File input doesn't exist"
}</syntaxhighlight>
 
=={{header|Prolog}}==
 
{{works with|SWI-Prolog|6.6}}
 
<syntaxhighlight lang="prolog">
 
exists_file('input.txt'),
Line 2,517 ⟶ 2,631:
 
</syntaxhighlight>
 
=={{header|PureBasic}}==
<syntaxhighlight lang=PureBasic"purebasic">result = ReadFile(#PB_Any, "input.txt")
If result>0 : Debug "this local file exists"
Else : Debug "result=" +Str(result) +" so this local file is missing"
Line 2,538 ⟶ 2,651:
Else : Debug "result=" +Str(result) +" so this root directory is missing"
EndIf </syntaxhighlight>
 
=={{header|Python}}==
 
<syntaxhighlight lang="python">import os
 
os.path.isfile("input.txt")
Line 2,549 ⟶ 2,661:
 
The more generic [https://docs.python.org/3/library/os.path.html#os.path.exists <code>os.path.exists(path)</code>] function will return True if the path exists, being it either a regular file or a directory.
 
=={{header|QB64}}==
<syntaxhighlight lang="qbasic">$NOPREFIX
PRINT DIREXISTS("docs")
PRINT DIREXISTS("\docs")
PRINT FILEEXISTS("input.txt")
PRINT FILEEXISTS("\input.txt")</syntaxhighlight>
 
=={{header|R}}==
<syntaxhighlight lang=R"r">file.exists("input.txt")
file.exists("/input.txt")
file.exists("docs")
Line 2,570 ⟶ 2,680:
This works with special names:
 
<syntaxhighlight lang=R"r">file.exists("`Abdu'l-Bahá.txt")</syntaxhighlight>
 
=={{header|Racket}}==
 
<syntaxhighlight lang=Racket"racket">
#lang racket
 
Line 2,590 ⟶ 2,699:
(file-exists? "docs")))
</syntaxhighlight>
 
=={{header|Raku}}==
(formerly Perl 6)
<syntaxhighlight lang="raku" line>
my $path = "/etc/passwd";
say $path.IO.e ?? "Exists" !! "Does not exist";
Line 2,606 ⟶ 2,714:
<code>when</code> internally uses the smart match operator <code>~~</code>, so <code>when :e</code> really does <code>$given ~~ :e</code> instead of the method call <code>$given.e</code>; both test whether the file exists.
 
<syntaxhighlight lang="raku" line>
run ('touch', "♥ Unicode.txt");
 
Line 2,612 ⟶ 2,720:
say "♥ Unicode.txt".IO ~~ :e; # same
</syntaxhighlight>
 
=={{header|Raven}}==
 
<syntaxhighlight lang="raven">'input.txt' exists if 'input.txt exists' print
'/input.txt' exists if '/input.txt exists' print
'docs' isdir if 'docs exists and is a directory' print
'/docs' isdir if '/docs exists and is a directory' print</syntaxhighlight>
 
=={{header|REBOL}}==
<syntaxhighlight lang=REBOL"rebol">exists? %input.txt
exists? %docs/
 
exists? %/input.txt
exists? %/docs/</syntaxhighlight>
 
=={{header|Red}}==
<syntaxhighlight lang=Red"red">exists? %input.txt
exists? %docs/
exists? %/c/input.txt
Line 2,637 ⟶ 2,742:
>> exists? %`Abdu'l-Bahá.txt
== true</syntaxhighlight>
 
=={{header|REXX}}==
===version 1===
Line 2,643 ⟶ 2,747:
{{works with|Personal REXX}}
{{works with|Regina}}
<syntaxhighlight lang="rexx">/*REXX program creates a new empty file and directory in current directory and root dir.*/
fn= 'input.txt' /*default name of a file. */
dn= 'docs' /*default name of a directory (folder).*/
Line 2,670 ⟶ 2,774:
{{works with|ARexx}}
{{works with|Regina 3.8 and later, with options: &nbsp; AREXX_BIFS &nbsp; AREXX_SEMANTICS}}
<syntaxhighlight lang="rexx">
/* Check if a file already exists */
filename='file.txt'
Line 2,680 ⟶ 2,784:
RETURN 1
</syntaxhighlight>
 
=={{header|Ring}}==
<syntaxhighlight lang="ring">
aFile = "C:\Ring\ReadMe.txt"
see aFile
Line 2,688 ⟶ 2,791:
else see " doesn't exist" + nl ok
</syntaxhighlight>
 
=={{header|RLaB}}==
 
RLaB provides two user functions for the task, ''isfile'' and ''isdir''.
<syntaxhighlight lang=RLaB"rlab">
>> isdir("docs")
0
Line 2,698 ⟶ 2,800:
0
</syntaxhighlight>
=={{header|RPL}}==
The 2 functions below take a word as an argument and return a boolean stating the presence or not of a 'file' (a 'variable' in RPL jargon) or a directory corresponding to the word.
« VARS SWAP POS
» '<span style="color:blue">ISHERE?</span>' STO
« PATH HOME
VARS ROT POS
SWAP EVAL <span style="color:grey">@ Back to initial directory</span>
» '<span style="color:blue">ISHOME?</span>' STO
 
=={{header|Ruby}}==
<code>File.existsexist?</code> only checks if a file exists; it can be a regular file, a directory, or something else. <code>File.file?</code> or <code>File.directory?</code> checks for a regular file or a directory. Ruby also allows <code>FileTest.file?</code> or <code>FileTest.directory?</code>.
 
<syntaxhighlight lang="ruby">File.file?("input.txt")
File.file?("/input.txt")
File.directory?("docs")
Line 2,709 ⟶ 2,820:
The next program runs all four checks and prints the results.
 
<syntaxhighlight lang="ruby">["input.txt", "/input.txt"].each { |f|
printf "%s is a regular file? %s\n", f, File.file?(f) }
["docs", "/docs"].each { |d|
Line 2,715 ⟶ 2,826:
 
=={{header|Run BASIC}}==
<syntaxhighlight lang="runbasic">files #f,"input.txt"
if #f hasanswer() = 1 then print "File does not exist"
files #f,"docs"
Line 2,721 ⟶ 2,832:
if #f isDir() = 0 then print "This is a directory"
</syntaxhighlight>
 
=={{header|Rust}}==
<syntaxhighlight lang="rust">use std::fs;
 
fn main() {
Line 2,742 ⟶ 2,852:
}
</syntaxhighlight>
 
=={{header|Scala}}==
{{libheader|Scala}}<syntaxhighlight lang="scala">import java.nio.file.{ Files, FileSystems }
 
object FileExistsTest extends App {
Line 2,761 ⟶ 2,870:
List("output.txt", separator + "output.txt", "docs", separator + "docs" + separator).foreach(test)
}</syntaxhighlight>
 
=={{header|Scheme}}==
{{works with|Scheme|R6RS}}[http://www.r6rs.org/final/html/r6rs-lib/r6rs-lib-Z-H-10.html]
<syntaxhighlight lang="scheme">(file-exists? filename)</syntaxhighlight>
 
=={{header|Seed7}}==
 
<syntaxhighlight lang="seed7">$ include "seed7_05.s7i";
 
const proc: main is func
Line 2,777 ⟶ 2,884:
writeln(fileType("/docs") = FILE_DIR);
end func;</syntaxhighlight>
 
=={{header|SenseTalk}}==
<syntaxhighlight lang="sensetalk">
put file "input.txt" exists
put folder "docs" exists
Line 2,786 ⟶ 2,892:
put there is a folder "/docs"
</syntaxhighlight>
 
=={{header|Sidef}}==
<syntaxhighlight lang="ruby"># Here
say (Dir.cwd + %f'input.txt' -> is_file);
say (Dir.cwd + %d'docs' -> is_dir);
Line 2,796 ⟶ 2,901:
say (Dir.root + %d'docs' -> is_dir);</syntaxhighlight>
NOTE: To check only for existence, use the method ''exists''
 
=={{header|Slate}}==
<syntaxhighlight lang="slate">(File newNamed: 'input.txt') exists
(File newNamed: '/input.txt') exists
(Directory root / 'input.txt') exists
(Directory newNamed: 'docs') exists
(Directory newNamed: '/docs') exists</syntaxhighlight>
 
=={{header|Smalltalk}}==
 
[[Squeak]] has no notion of 'current directory' because it isn't tied to the shell that created it.
 
<syntaxhighlight lang="smalltalk">FileDirectory new fileExists: 'c:\serial'.
(FileDirectory on: 'c:\') directoryExists: 'docs'.</syntaxhighlight>
 
In [[GNU Smalltalk]] instead you can do:
 
<syntaxhighlight lang="smalltalk">(Directory name: 'docs') exists ifTrue: [ ... ]
(Directory name: 'c:\docs') exists ifTrue: [ ... ]
(File name: 'serial') isFile ifTrue: [ ... ]
Line 2,819 ⟶ 2,922:
 
Using ''exists'' in the third and fourth case will return true for directories too.
 
=={{header|Standard ML}}==
<syntaxhighlight lang="sml">OS.FileSys.access ("input.txt", []);
OS.FileSys.access ("docs", []);
OS.FileSys.access ("/input.txt", []);
OS.FileSys.access ("/docs", []);</syntaxhighlight>
 
=={{header|Stata}}==
Mata has functions to check the existence of files and directories:
<syntaxhighlight lang="stata">mata
fileexists("input.txt")
direxists("docs")
Line 2,835 ⟶ 2,936:
It's not as straightforward in Stata's macro language. For files, use [http://www.stata.com/help.cgi?confirm confirm]. Since it throws an error when the file does not exist, use [http://www.stata.com/help.cgi?capture capture] and check [http://www.stata.com/help.cgi?_variables _rc] afterwards.
 
<syntaxhighlight lang="stata">capture confirm file input.txt
if !_rc {
* do something if the file exists
Line 2,842 ⟶ 2,943:
It's not possible to check the existence of a directory with confirm. One may use the [https://ideas.repec.org/c/boc/bocode/s435507.html confirmdir] package from SSC. The confirmdir command saves the current directory, then tries to chdir to the directory to test (with capture to prevent an error). Then the value of _rc is put in a [http://www.stata.com/help.cgi?return stored result]. Example of use:
 
<syntaxhighlight lang="stata">confirmdir docs
if !`r(confirmdir)' {
* do something if the directory exists
Line 2,849 ⟶ 2,950:
The command works with special names, but one has to be careful: the name "`Abdu'l-Bahá.txt" contains a backquote, which is used to denote macros in Stata. So this character must be escaped with a backslash:
 
<syntaxhighlight lang="stata">confirm file "\`Abdu'l-Bahá.txt"</syntaxhighlight>
 
=={{header|Tcl}}==
Taking the meaning of the task from the DOS example: <!-- multiline “if” because of formatting -->
<syntaxhighlight lang="tcl">if { [file exists "input.txt"] } {
puts "input.txt exists"
}
Line 2,869 ⟶ 2,969:
}</syntaxhighlight>
Note that these operations do not require the use of <tt>file nativename</tt> on either Windows or any version of Unix.
 
=={{header|Toka}}==
 
<syntaxhighlight lang="toka">[ "R" file.open dup 0 <> [ dup file.close ] ifTrue 0 <> ] is exists?
" input.txt" exists? .
" /input.txt" exists? .
" docs" exists? .
" /docs" exists? .</syntaxhighlight>
 
=={{header|True BASIC}}==
<syntaxhighlight lang="truebasic">SUB opener (a$)
WHEN EXCEPTION IN
OPEN #1: NAME f$
Line 2,903 ⟶ 3,001:
CALL opener (f$)
END</syntaxhighlight>
 
=={{header|TUSCRIPT}}==
<syntaxhighlight lang="tuscript">
$$ MODE TUSCRIPT
file="input.txt",directory="docs"
Line 2,924 ⟶ 3,021:
@@@@@@@@ directory docs not exists @@@@@@@@
</pre>
 
=={{header|UNIX Shell}}==
<syntaxhighlight lang="bash">test -f input.txt
test -f /input.txt
test -d docs
Line 2,933 ⟶ 3,029:
The next program runs all four checks and prints the results.
 
<syntaxhighlight lang="bash">for f in input.txt /input.txt; do
test -f "$f" && r=true || r=false
echo "$f is a regular file? $r"
Line 2,941 ⟶ 3,037:
echo "$d is a directory? $r"
done</syntaxhighlight>
 
=={{header|Ursa}}==
The easiest way to do this in Ursa is to attempt to open the file in question. If it doesn't exist, an ioerror will be thrown.
<syntaxhighlight lang="ursa">def exists (string filename)
decl file f
try
Line 2,953 ⟶ 3,048:
end try
end exists</syntaxhighlight>
 
=={{header|Vala}}==
This needs to be compiled with the gio-2.0 package: valac --pkg gio-2.0 check_that_file_exists.vala
<syntaxhighlight lang="vala">int main (string[] args) {
string[] files = {"input.txt", "docs", Path.DIR_SEPARATOR_S + "input.txt", Path.DIR_SEPARATOR_S + "docs"};
foreach (string f in files) {
Line 2,965 ⟶ 3,059:
}</syntaxhighlight>
A more complete version which informs whether the existing file is a regular file or a directory
<syntaxhighlight lang="vala">int main (string[] args) {
string[] files = {"input.txt", "docs", Path.DIR_SEPARATOR_S + "input.txt", Path.DIR_SEPARATOR_S + "docs"};
foreach (var f in files) {
Line 2,985 ⟶ 3,079:
return 0;
}</syntaxhighlight>
 
=={{header|VBA}}==
 
<syntaxhighlight lang="vb">
Option Explicit
 
Line 3,008 ⟶ 3,101:
End Function
</syntaxhighlight>
 
=={{header|VBScript}}==
 
<syntaxhighlight lang="vbscript">Set FSO = CreateObject("Scripting.FileSystemObject")
 
Function FileExists(strFile)
Line 3,047 ⟶ 3,139:
 
</syntaxhighlight>
 
=={{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.
<syntaxhighlight lang="vedit">// In current directory
if (File_Exist("input.txt")) { M("input.txt exists\n") } else { M("input.txt does not exist\n") }
if (File_Exist("docs/nul", NOERR)) { M("docs exists\n") } else { M("docs does not exist\n") }
Line 3,057 ⟶ 3,148:
if (File_Exist("/input.txt")) { M("/input.txt exists\n") } else { M("/input.txt does not exist\n") }
if (File_Exist("/docs/nul", NOERR)) { M("/docs exists\n") } else { M("/docs does not exist\n") }</syntaxhighlight>
 
=={{header|Visual Basic}}==
{{works with|Visual Basic|VB6 Standard}}
The proposed solutions for VBA and VBScript work in VB6 as well, however here's a Windows API based approach:
<syntaxhighlight lang="vb">
'declarations:
Public Declare Function GetFileAttributes Lib "kernel32" _
Line 3,079 ⟶ 3,169:
End Function
</syntaxhighlight>
 
=={{header|Visual Basic .NET}}==
'''Platform:''' [[.NET]]
 
{{works with|Visual Basic .NET|9.0+}}
<syntaxhighlight lang="vbnet">'Current Directory
Console.WriteLine(If(IO.Directory.Exists("docs"), "directory exists", "directory doesn't exists"))
Console.WriteLine(If(IO.Directory.Exists("output.txt"), "file exists", "file doesn't exists"))
Line 3,097 ⟶ 3,186:
Console.WriteLine(If(IO.Directory.Exists(IO.Path.DirectorySeparatorChar & "output.txt"), _
"file exists", "file doesn't exists"))</syntaxhighlight>
=={{header|V (Vlang)}}==
 
<syntaxhighlight lang="go">// Check file exists in V
=={{header|Vlang}}==
<syntaxhighlight lang=go>// Check file exists in V
// Tectonics: v run check-that-file-exists.v
module main
Line 3,137 ⟶ 3,225:
os.is_file('empty.txt'): true
os.is_file("`Abdu'l-Bahá.txt"): true</pre>
 
 
=={{header|Wren}}==
Line 3,145 ⟶ 3,232:
 
Since in Linux an ''empty'' directory has a size of 4K bytes, we check the number of files it contains to confirm that it's empty.
<syntaxhighlight lang=ecmascript"wren">import "io" for Directory, File
 
for (name in ["input.txt", "`Abdu'l-Bahá.txt"]) {
Line 3,174 ⟶ 3,261:
Attempting to open a non-existent file or directory will cause an error.
A zero-length file is detected as existing.
<syntaxhighlight lang=XPL0"xpl0">
int FD; \file descriptor
[Trap(false); \prevent errors from aborting program
Line 3,186 ⟶ 3,273:
if GetErr then Text(0, "/dir doesn't exist^m^j");
]</syntaxhighlight>
 
=={{header|Yabasic}}==
<syntaxhighlight lang=Yabasic"yabasic">open "foo.bar" for writing as #1
print #1 "Hallo !"
close #1
Line 3,195 ⟶ 3,281:
if (not open(1,"buzz.bar")) print "Could not open 'buzz.bar' for reading"
</syntaxhighlight>
 
=={{header|zkl}}==
<syntaxhighlight lang="zkl">File.exists("input.txt") //--> True (in this case a sym link)
File.exists("/input.txt") //-->False
File.isDir("/") //-->True
File.isDir("docs") //-->False
</syntaxhighlight>
 
{{omit from|Befunge|No filesystem support}}
{{omit from|EasyLang}}
{{omit from|HTML}}
{{omit from|Scratch|No filesystem support}}
885

edits