Check that file exists: Difference between revisions

Content added Content deleted
m (syntax highlighting fixup automation)
m (Automated syntax highlighting fixup (second round - minor fixes))
Line 1: Line 1:
{{task|File System Operations}} [[Category:Simple]]
[[Category:Simple]]
{{task|File System Operations}}

;Task:
;Task:
Verify that a file called     '''input.txt'''     and   a directory called     '''docs'''     exist.
Verify that a file called     '''input.txt'''     and   a directory called     '''docs'''     exist.
Line 14: Line 14:
:::* &nbsp; an unusual filename: &nbsp; <big> ''' `Abdu'l-Bahá.txt ''' </big>
:::* &nbsp; an unusual filename: &nbsp; <big> ''' `Abdu'l-Bahá.txt ''' </big>
<br><br>
<br><br>

=={{header|11l}}==
=={{header|11l}}==
{{Trans|Python}}
{{Trans|Python}}
<syntaxhighlight lang=11l>fs:is_file(‘input.txt’)
<syntaxhighlight lang="11l">fs:is_file(‘input.txt’)
fs:is_file(‘/input.txt’)
fs:is_file(‘/input.txt’)
fs:is_dir(‘docs’)
fs:is_dir(‘docs’)
fs:is_dir(‘/docs’)</syntaxhighlight>
fs:is_dir(‘/docs’)</syntaxhighlight>

=={{header|AArch64 Assembly}}==
=={{header|AArch64 Assembly}}==
{{works with|as|Raspberry Pi 3B version Buster 64 bits}}
{{works with|as|Raspberry Pi 3B version Buster 64 bits}}
<syntaxhighlight lang=AArch64 Assembly>
<syntaxhighlight lang="aarch64 assembly">
/* ARM assembly AARCH64 Raspberry PI 3B */
/* ARM assembly AARCH64 Raspberry PI 3B */
/* program verifFic64.s */
/* program verifFic64.s */
Line 137: Line 135:
.include "../includeARM64.inc"
.include "../includeARM64.inc"
</syntaxhighlight>
</syntaxhighlight>

=={{header|Action!}}==
=={{header|Action!}}==
<syntaxhighlight lang=Action!>BYTE lastError
<syntaxhighlight lang="action!">BYTE lastError


PROC MyError(BYTE errCode)
PROC MyError(BYTE errCode)
Line 186: Line 183:
File "D:DOS.SYS" exists.
File "D:DOS.SYS" exists.
</pre>
</pre>

=={{header|Ada}}==
=={{header|Ada}}==
This example should work with any Ada 95 compiler.
This example should work with any Ada 95 compiler.
<syntaxhighlight lang=ada>with Ada.Text_IO; use Ada.Text_IO;
<syntaxhighlight lang="ada">with Ada.Text_IO; use Ada.Text_IO;


procedure File_Exists is
procedure File_Exists is
Line 207: Line 203:
end File_Exists;</syntaxhighlight>
end File_Exists;</syntaxhighlight>
This example should work with any Ada 2005 compiler.
This example should work with any Ada 2005 compiler.
<syntaxhighlight lang=ada>with Ada.Text_IO; use Ada.Text_IO;
<syntaxhighlight lang="ada">with Ada.Text_IO; use Ada.Text_IO;
with Ada.Directories; use Ada.Directories;
with Ada.Directories; use Ada.Directories;


Line 227: Line 223:
Print_Dir_Exist ("/docs");
Print_Dir_Exist ("/docs");
end File_Exists;</syntaxhighlight>
end File_Exists;</syntaxhighlight>

=={{header|Aikido}}==
=={{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.
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>
<syntaxhighlight lang="aikido">
function exists (filename) {
function exists (filename) {
return stat (filename) != null
return stat (filename) != null
Line 241: Line 236:


</syntaxhighlight>
</syntaxhighlight>

=={{header|ALGOL 68}}==
=={{header|ALGOL 68}}==
{{works with|ALGOL 68G|Any - tested with release 2.8.3.win32}}
{{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.
Uses the Algol 68G specific "file is directory" procedure to test for the existence of directories.
<syntaxhighlight lang=algol68># Check files and directories exist #
<syntaxhighlight lang="algol68"># Check files and directories exist #


# check a file exists by attempting to open it for input #
# check a file exists by attempting to open it for input #
Line 285: Line 279:
test directory exists( "docs" );
test directory exists( "docs" );
test directory exists( "\docs" )</syntaxhighlight>
test directory exists( "\docs" )</syntaxhighlight>

=={{header|Amazing Hopper}}==
=={{header|Amazing Hopper}}==
Version: hopper-FLOW!:
Version: hopper-FLOW!:
<syntaxhighlight lang=Amazing Hopper>
<syntaxhighlight lang="amazing hopper">
#include <flow.h>
#include <flow.h>


Line 317: Line 310:
$
$
</pre>
</pre>

=={{header|APL}}==
=={{header|APL}}==
<syntaxhighlight lang=apl>
<syntaxhighlight lang="apl">
h ← ⎕fio['fopen'] 'input.txt'
h ← ⎕fio['fopen'] 'input.txt'
h
h
Line 338: Line 330:
¯1
¯1
</syntaxhighlight>
</syntaxhighlight>

=={{header|AppleScript}}==
=={{header|AppleScript}}==
{{Trans|JavaScript}}
{{Trans|JavaScript}}
(macOS JavaScript for Automation)
(macOS JavaScript for Automation)
<syntaxhighlight lang=AppleScript>use framework "Foundation" -- YOSEMITE OS X onwards
<syntaxhighlight lang="applescript">use framework "Foundation" -- YOSEMITE OS X onwards
use scripting additions
use scripting additions


Line 440: Line 431:
The last four are returned by `doesDirectoryExist`,
The last four are returned by `doesDirectoryExist`,
which yields false for simple files, and true for directories.
which yields false for simple files, and true for directories.
<syntaxhighlight lang=AppleScript>{true, true, true, true, false, false, true, true}</syntaxhighlight>
<syntaxhighlight lang="applescript">{true, true, true, true, false, false, true, true}</syntaxhighlight>

=={{header|Applesoft BASIC}}==
=={{header|Applesoft BASIC}}==
The error code for FILE NOT FOUND is 6.
The error code for FILE NOT FOUND is 6.
<syntaxhighlight lang=ApplesoftBasic>100 F$ = "THAT FILE"
<syntaxhighlight lang="applesoftbasic">100 F$ = "THAT FILE"
110 T$(0) = "DOES NOT EXIST."
110 T$(0) = "DOES NOT EXIST."
120 T$(1) = "EXISTS."
120 T$(1) = "EXISTS."
Line 466: Line 456:
360 RETURN
360 RETURN
</syntaxhighlight>
</syntaxhighlight>

=={{header|ARM Assembly}}==
=={{header|ARM Assembly}}==
{{works with|as|Raspberry Pi}}
{{works with|as|Raspberry Pi}}
<syntaxhighlight lang=ARM Assembly>
<syntaxhighlight lang="arm assembly">
/* ARM assembly Raspberry PI */
/* ARM assembly Raspberry PI */
/* program verifFic.s */
/* program verifFic.s */
Line 594: Line 583:
bx lr /* return */
bx lr /* return */
</syntaxhighlight>
</syntaxhighlight>

=={{header|Arturo}}==
=={{header|Arturo}}==
<syntaxhighlight lang=rebol>checkIfExists: function [fpath][
<syntaxhighlight lang="rebol">checkIfExists: function [fpath][
(or? exists? fpath
(or? exists? fpath
exists? .directory fpath)? -> print [fpath "exists"]
exists? .directory fpath)? -> print [fpath "exists"]
Line 607: Line 595:
checkIfExists "/input.txt"
checkIfExists "/input.txt"
checkIfExists "/docs"</syntaxhighlight>
checkIfExists "/docs"</syntaxhighlight>

=={{header|AutoHotkey}}==
=={{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.
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: Line 600:
Another option is AutoHotkey's IfExist/IfNotExist command
Another option is AutoHotkey's IfExist/IfNotExist command


<syntaxhighlight lang=autohotkey>; FileExist() function examples
<syntaxhighlight lang="autohotkey">; FileExist() function examples
ShowFileExist("input.txt")
ShowFileExist("input.txt")
ShowFileExist("\input.txt")
ShowFileExist("\input.txt")
Line 646: Line 633:
Return
Return
}</syntaxhighlight>
}</syntaxhighlight>

=={{header|AWK}}==
=={{header|AWK}}==
{{works with|gawk}}
{{works with|gawk}}
<syntaxhighlight lang=awk>@load "filefuncs"
<syntaxhighlight lang="awk">@load "filefuncs"


function exists(name ,fd) {
function exists(name ,fd) {
Line 665: Line 651:


Portable getline method. Also works in a Windows environment.
Portable getline method. Also works in a Windows environment.
<syntaxhighlight lang=AWK>#
<syntaxhighlight lang="awk">#
# Check if file or directory exists, even 0-length file.
# Check if file or directory exists, even 0-length file.
# Return 0 if not exist, 1 if exist
# Return 0 if not exist, 1 if exist
Line 693: Line 679:
{{works with|gawk}}
{{works with|gawk}}
Check file(s) existence
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>
<syntaxhighlight lang="text">gawk 'BEGINFILE{if (ERRNO) {print "Not exist."; nextfile} else {print "Exist."; nextfile}}' input.txt input-missing.txt</syntaxhighlight>

=={{header|Axe}}==
=={{header|Axe}}==
<syntaxhighlight lang=axe>If GetCalc("appvINPUT")
<syntaxhighlight lang="axe">If GetCalc("appvINPUT")
Disp "EXISTS",i
Disp "EXISTS",i
Else
Else
Disp "DOES NOT EXIST",i
Disp "DOES NOT EXIST",i
End</syntaxhighlight>
End</syntaxhighlight>

=={{header|BASIC}}==
=={{header|BASIC}}==
{{works with|QBasic}}
{{works with|QBasic}}
<syntaxhighlight lang=qbasic>
<syntaxhighlight lang="qbasic">
ON ERROR GOTO ohNo
ON ERROR GOTO ohNo
f$ = "input.txt"
f$ = "input.txt"
Line 737: Line 721:
You can also check for a directory by trying to enter it.
You can also check for a directory by trying to enter it.


<syntaxhighlight lang=qbasic>
<syntaxhighlight lang="qbasic">
ON ERROR GOTO ohNo
ON ERROR GOTO ohNo
d$ = "docs"
d$ = "docs"
Line 758: Line 742:
Later versions of MS-compatible BASICs include the <CODE>DIR$</CODE> keyword, which makes this pretty trivial.
Later versions of MS-compatible BASICs include the <CODE>DIR$</CODE> keyword, which makes this pretty trivial.


<syntaxhighlight lang=qbasic>
<syntaxhighlight lang="qbasic">
f$ = "input.txt"
f$ = "input.txt"
GOSUB opener
GOSUB opener
Line 783: Line 767:


==={{header|BaCon}}===
==={{header|BaCon}}===
<syntaxhighlight lang=freebasic>' File exists
<syntaxhighlight lang="freebasic">' File exists
f$ = "input.txt"
f$ = "input.txt"
d$ = "docs"
d$ = "docs"
Line 810: Line 794:
==={{header|Commodore BASIC}}===
==={{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".
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
<syntaxhighlight lang="gwbasic">10 REM CHECK FILE EXISTS
15 ER=0:EM$="":MSG$="FILE EXISTS."
15 ER=0:EM$="":MSG$="FILE EXISTS."
20 PRINT CHR$(147);:REM CLEAR SCREEN
20 PRINT CHR$(147);:REM CLEAR SCREEN
Line 837: Line 821:
ENTER FILENAME TO CHECK? NOFILE.DOC
ENTER FILENAME TO CHECK? NOFILE.DOC
'NOFILE.DOC' IS NOT HERE.</pre>
'NOFILE.DOC' IS NOT HERE.</pre>

=={{header|BASIC256}}==
=={{header|BASIC256}}==
<syntaxhighlight lang=BASIC256>subroutine opener (filename$)
<syntaxhighlight lang="basic256">subroutine opener (filename$)
if exists(filename$) then
if exists(filename$) then
print filename$; " exists"
print filename$; " exists"
Line 854: Line 837:
call opener ("`Abdu'l-Bahá.txt"))
call opener ("`Abdu'l-Bahá.txt"))
end</syntaxhighlight>
end</syntaxhighlight>

=={{header|Batch File}}==
=={{header|Batch File}}==
<syntaxhighlight lang=dos>if exist input.txt echo The following file called input.txt exists.
<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 \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.
if exist \docs\ echo The following directory called \docs\ exists.</syntaxhighlight>
if exist \docs\ echo The following directory called \docs\ exists.</syntaxhighlight>

=={{header|BBC BASIC}}==
=={{header|BBC BASIC}}==
<syntaxhighlight lang=bbcbasic> test% = OPENIN("input.txt")
<syntaxhighlight lang="bbcbasic"> test% = OPENIN("input.txt")
IF test% THEN
IF test% THEN
CLOSE #test%
CLOSE #test%
Line 885: Line 866:
PRINT "Directory \docs exists"
PRINT "Directory \docs exists"
ENDIF</syntaxhighlight>
ENDIF</syntaxhighlight>

=={{header|BQN}}==
=={{header|BQN}}==


Line 892: Line 872:
Takes filename as a command line argument, tells whether it exists.
Takes filename as a command line argument, tells whether it exists.


<syntaxhighlight lang=BQN>fname ← ⊑args
<syntaxhighlight lang="bqn">fname ← ⊑args
•Out fname∾" Does not exist"‿" Exists"⊑˜•File.exists fname</syntaxhighlight>
•Out fname∾" Does not exist"‿" Exists"⊑˜•File.exists fname</syntaxhighlight>

=={{header|C}}==
=={{header|C}}==
{{libheader|POSIX}}
{{libheader|POSIX}}
<syntaxhighlight lang=c>#include <sys/types.h>
<syntaxhighlight lang="c">#include <sys/types.h>
#include <sys/stat.h>
#include <sys/stat.h>
#include <stdio.h>
#include <stdio.h>
Line 925: Line 904:
return 0;
return 0;
}</syntaxhighlight>
}</syntaxhighlight>

=={{header|C sharp|C#}}==
=={{header|C sharp|C#}}==


<syntaxhighlight lang=csharp>using System.IO;
<syntaxhighlight lang="csharp">using System.IO;


Console.WriteLine(File.Exists("input.txt"));
Console.WriteLine(File.Exists("input.txt"));
Line 934: Line 912:
Console.WriteLine(Directory.Exists("docs"));
Console.WriteLine(Directory.Exists("docs"));
Console.WriteLine(Directory.Exists("/docs"));</syntaxhighlight>
Console.WriteLine(Directory.Exists("/docs"));</syntaxhighlight>

=={{header|C++}}==
=={{header|C++}}==
{{libheader|boost}}
{{libheader|boost}}
<syntaxhighlight lang=cpp>#include "boost/filesystem.hpp"
<syntaxhighlight lang="cpp">#include "boost/filesystem.hpp"
#include <string>
#include <string>
#include <iostream>
#include <iostream>
Line 962: Line 939:
testfile("/docs");
testfile("/docs");
}</syntaxhighlight>
}</syntaxhighlight>

=={{header|Clojure}}==
=={{header|Clojure}}==
<syntaxhighlight lang=clojure>
<syntaxhighlight lang="clojure">


(dorun (map #(.exists (clojure.java.io/as-file %)) '("/input.txt" "/docs" "./input.txt" "./docs")))
(dorun (map #(.exists (clojure.java.io/as-file %)) '("/input.txt" "/docs" "./input.txt" "./docs")))


</syntaxhighlight>
</syntaxhighlight>

=={{header|COBOL}}==
=={{header|COBOL}}==
{{works with|GnuCOBOL}} and other compilers with this system call extension
{{works with|GnuCOBOL}} and other compilers with this system call extension
<syntaxhighlight lang=COBOL> identification division.
<syntaxhighlight lang="cobol"> identification division.
program-id. check-file-exist.
program-id. check-file-exist.


Line 1,059: Line 1,034:
error: CBL_CHECK_FILE_EXIST +000000035 /docs/</pre>
error: CBL_CHECK_FILE_EXIST +000000035 /docs/</pre>
Errors due to file and dir not existing in root directory for this test pass
Errors due to file and dir not existing in root directory for this test pass

=={{header|CoffeeScript}}==
=={{header|CoffeeScript}}==
{{works with|Node.js}}
{{works with|Node.js}}
<syntaxhighlight lang=coffeescript>
<syntaxhighlight lang="coffeescript">
fs = require 'fs'
fs = require 'fs'
path = require 'path'
path = require 'path'
Line 1,086: Line 1,060:


</syntaxhighlight>
</syntaxhighlight>

=={{header|Common Lisp}}==
=={{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.
''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"))
<syntaxhighlight lang="lisp">(if (probe-file (make-pathname :name "input.txt"))
(print "rel file exists"))
(print "rel file exists"))
(if (probe-file (make-pathname :directory '(:absolute "") :name "input.txt"))
(if (probe-file (make-pathname :directory '(:absolute "") :name "input.txt"))
Line 1,105: Line 1,078:


{{libheader|CL-FAD}}
{{libheader|CL-FAD}}
<syntaxhighlight lang=lisp>(if (cl-fad:directory-exists-p (make-pathname :directory '(:relative "docs")))
<syntaxhighlight lang="lisp">(if (cl-fad:directory-exists-p (make-pathname :directory '(:relative "docs")))
(print "rel directory exists")
(print "rel directory exists")
(print "rel directory does not exist"))</syntaxhighlight>
(print "rel directory does not exist"))</syntaxhighlight>

=={{header|Crystal}}==
=={{header|Crystal}}==
<syntaxhighlight lang=ruby>def check_file(filename : String)
<syntaxhighlight lang="ruby">def check_file(filename : String)
if File.directory?(filename)
if File.directory?(filename)
puts "#{filename} is a directory"
puts "#{filename} is a directory"
Line 1,124: Line 1,096:
check_file("/input.txt")
check_file("/input.txt")
check_file("/docs")</syntaxhighlight>
check_file("/docs")</syntaxhighlight>

=={{header|D}}==
=={{header|D}}==
<syntaxhighlight lang=d>import std.stdio, std.file, std.path;
<syntaxhighlight lang="d">import std.stdio, std.file, std.path;


void verify(in string name) {
void verify(in string name) {
Line 1,149: Line 1,120:
'\input.txt' doesn't exist
'\input.txt' doesn't exist
'\docs' doesn't exist</pre>
'\docs' doesn't exist</pre>

=={{header|DBL}}==
=={{header|DBL}}==
<syntaxhighlight lang=DBL>;
<syntaxhighlight lang="dbl">;
; Check file and directory exists for DBL version 4 by Dario B.
; Check file and directory exists for DBL version 4 by Dario B.
;
;
Line 1,186: Line 1,156:
CLOSE 2
CLOSE 2
STOP</syntaxhighlight>
STOP</syntaxhighlight>

=={{header|DCL}}==
=={{header|DCL}}==
<syntaxhighlight lang=DCL>$ if f$search( "input.txt" ) .eqs. ""
<syntaxhighlight lang="dcl">$ if f$search( "input.txt" ) .eqs. ""
$ then
$ then
$ write sys$output "input.txt not found"
$ write sys$output "input.txt not found"
Line 1,219: Line 1,188:
[000000]input.txt not found
[000000]input.txt not found
directory [000000]docs not found</pre>
directory [000000]docs not found</pre>

=={{header|Delphi}}==
=={{header|Delphi}}==
<syntaxhighlight lang=Delphi>program EnsureFileExists;
<syntaxhighlight lang="delphi">program EnsureFileExists;


{$APPTYPE CONSOLE}
{$APPTYPE CONSOLE}
Line 1,249: Line 1,217:
Writeln('Directory "\docs" does not exists.');
Writeln('Directory "\docs" does not exists.');
end.</syntaxhighlight>
end.</syntaxhighlight>

=={{header|E}}==
=={{header|E}}==
<syntaxhighlight lang=e>for file in [<file:input.txt>,
<syntaxhighlight lang="e">for file in [<file:input.txt>,
<file:///input.txt>] {
<file:///input.txt>] {
require(file.exists(), fn { `$file is missing!` })
require(file.exists(), fn { `$file is missing!` })
Line 1,262: Line 1,229:
require(file.isDirectory(), fn { `$file is not a directory!` })
require(file.isDirectory(), fn { `$file is not a directory!` })
}</syntaxhighlight>
}</syntaxhighlight>

=={{header|Elena}}==
=={{header|Elena}}==
ELENA 4.x :
ELENA 4.x :
<syntaxhighlight lang=elena>import system'io;
<syntaxhighlight lang="elena">import system'io;
import extensions;
import extensions;


Line 1,284: Line 1,250:
console.printLine("\docs directory ",Directory.assign("\docs").validatePath())
console.printLine("\docs directory ",Directory.assign("\docs").validatePath())
}</syntaxhighlight>
}</syntaxhighlight>

=={{header|Elixir}}==
=={{header|Elixir}}==
<syntaxhighlight lang=Elixir>File.regular?("input.txt")
<syntaxhighlight lang="elixir">File.regular?("input.txt")
File.dir?("docs")
File.dir?("docs")
File.regular?("/input.txt")
File.regular?("/input.txt")
File.dir?("/docs")</syntaxhighlight>
File.dir?("/docs")</syntaxhighlight>

=={{header|Emacs Lisp}}==
=={{header|Emacs Lisp}}==
<syntaxhighlight lang=Lisp>(file-exists-p "input.txt")
<syntaxhighlight lang="lisp">(file-exists-p "input.txt")
(file-directory-p "docs")
(file-directory-p "docs")
(file-exists-p "/input.txt")
(file-exists-p "/input.txt")
Line 1,298: Line 1,262:


<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.
<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}}==
=={{header|Erlang}}==
<syntaxhighlight lang=erlang>#!/usr/bin/escript
<syntaxhighlight lang="erlang">#!/usr/bin/escript
existence( true ) ->"exists";
existence( true ) ->"exists";
existence( false ) ->"does not exist".
existence( false ) ->"does not exist".
Line 1,313: Line 1,276:
print_result( "Directory", "/docs", filelib:is_dir("/docs") ).
print_result( "Directory", "/docs", filelib:is_dir("/docs") ).
</syntaxhighlight>
</syntaxhighlight>

=={{header|Euphoria}}==
=={{header|Euphoria}}==
<syntaxhighlight lang=euphoria>include file.e
<syntaxhighlight lang="euphoria">include file.e


procedure ensure_exists(sequence name)
procedure ensure_exists(sequence name)
Line 1,337: Line 1,299:
ensure_exists("/input.txt")
ensure_exists("/input.txt")
ensure_exists("/docs")</syntaxhighlight>
ensure_exists("/docs")</syntaxhighlight>

=={{header|F_Sharp|F#}}==
=={{header|F_Sharp|F#}}==
<syntaxhighlight lang=fsharp>open System.IO
<syntaxhighlight lang="fsharp">open System.IO
File.Exists("input.txt")
File.Exists("input.txt")
Directory.Exists("docs")
Directory.Exists("docs")
File.Exists("/input.txt")
File.Exists("/input.txt")
Directory.Exists(@"\docs")</syntaxhighlight>
Directory.Exists(@"\docs")</syntaxhighlight>

=={{header|Factor}}==
=={{header|Factor}}==
<syntaxhighlight lang=factor>: print-exists? ( path -- )
<syntaxhighlight lang="factor">: print-exists? ( path -- )
[ write ": " write ] [ exists? "exists." "doesn't exist." ? print ] bi ;
[ write ": " write ] [ exists? "exists." "doesn't exist." ? print ] bi ;


{ "input.txt" "/input.txt" "docs" "/docs" } [ print-exists? ] each</syntaxhighlight>
{ "input.txt" "/input.txt" "docs" "/docs" } [ print-exists? ] each</syntaxhighlight>

=={{header|Forth}}==
=={{header|Forth}}==


<syntaxhighlight lang=forth>: .exists ( str len -- ) 2dup file-status nip 0= if ." exists" else ." does not exist" then type ;
<syntaxhighlight lang="forth">: .exists ( str len -- ) 2dup file-status nip 0= if ." exists" else ." does not exist" then type ;
s" input.txt" .exists
s" input.txt" .exists
s" /input.txt" .exists
s" /input.txt" .exists
s" docs" .exists
s" docs" .exists
s" /docs" .exists</syntaxhighlight>
s" /docs" .exists</syntaxhighlight>

=={{header|Fortran}}==
=={{header|Fortran}}==
{{works with|Fortran|90 and later}}
{{works with|Fortran|90 and later}}


Cannot check for directories in Fortran
Cannot check for directories in Fortran
<syntaxhighlight lang=fortran>LOGICAL :: file_exists
<syntaxhighlight lang="fortran">LOGICAL :: file_exists
INQUIRE(FILE="input.txt", EXIST=file_exists) ! file_exists will be TRUE if the file
INQUIRE(FILE="input.txt", EXIST=file_exists) ! file_exists will be TRUE if the file
! exists and FALSE otherwise
! exists and FALSE otherwise
Line 1,370: Line 1,328:
Actually, f90,f95 are able to deal with directory staff:
Actually, f90,f95 are able to deal with directory staff:


<syntaxhighlight lang=fortran>logical :: dir_e
<syntaxhighlight lang="fortran">logical :: dir_e
! a trick to be sure docs is a dir
! a trick to be sure docs is a dir
inquire( file="./docs/.", exist=dir_e )
inquire( file="./docs/.", exist=dir_e )
Line 1,379: Line 1,337:
call system('mkdir docs')
call system('mkdir docs')
end if</syntaxhighlight>
end if</syntaxhighlight>

=={{header|FreeBASIC}}==
=={{header|FreeBASIC}}==
<syntaxhighlight lang=freebasic>' FB 1.05.0 Win64
<syntaxhighlight lang="freebasic">' FB 1.05.0 Win64


' Enable FileExists() function to be used
' Enable FileExists() function to be used
Line 1,428: Line 1,385:
'c:\docs' exists
'c:\docs' exists
</pre>
</pre>

=={{header|Frink}}==
=={{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.
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>
<syntaxhighlight lang="frink">
checkFile[filename] :=
checkFile[filename] :=
{
{
Line 1,468: Line 1,424:
checkFile[normalizeUnicode[unusual, "NFD"]]
checkFile[normalizeUnicode[unusual, "NFD"]]
</syntaxhighlight>
</syntaxhighlight>

=={{header|Gambas}}==
=={{header|Gambas}}==
'''[https://gambas-playground.proko.eu/?gist=fa06b7cc43166fb0ab48e878d86e3d1b Click this link to run this code]'''
'''[https://gambas-playground.proko.eu/?gist=fa06b7cc43166fb0ab48e878d86e3d1b Click this link to run this code]'''
<syntaxhighlight lang=gambas>Public Sub Main()
<syntaxhighlight lang="gambas">Public Sub Main()


If Exist(User.Home &/ "input.txt") Then Print "'input.txt' does exist in the Home folder"
If Exist(User.Home &/ "input.txt") Then Print "'input.txt' does exist in the Home folder"
Line 1,491: Line 1,446:
'`Abdu'l-Bahá.txt' does exist (zero length and unusual name)
'`Abdu'l-Bahá.txt' does exist (zero length and unusual name)
</pre>
</pre>

=={{header|GAP}}==
=={{header|GAP}}==
<syntaxhighlight lang=gap>IsExistingFile("input.txt");
<syntaxhighlight lang="gap">IsExistingFile("input.txt");
IsDirectoryPath("docs");
IsDirectoryPath("docs");
IsExistingFile("/input.txt");
IsExistingFile("/input.txt");
IsDirectoryPath("/docs");</syntaxhighlight>
IsDirectoryPath("/docs");</syntaxhighlight>

=={{header|Genie}}==
=={{header|Genie}}==
<syntaxhighlight lang=genie>[indent=4]
<syntaxhighlight lang="genie">[indent=4]
/*
/*
Check file exists, in Genie
Check file exists, in Genie
Line 1,528: Line 1,481:


For the run, ''input.txt'' was zero length.
For the run, ''input.txt'' was zero length.

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


import (
import (
Line 1,554: Line 1,506:
printStat("/docs")
printStat("/docs")
}</syntaxhighlight>
}</syntaxhighlight>

=={{header|Groovy}}==
=={{header|Groovy}}==
<syntaxhighlight lang=groovy>println new File('input.txt').exists()
<syntaxhighlight lang="groovy">println new File('input.txt').exists()
println new File('/input.txt').exists()
println new File('/input.txt').exists()
println new File('docs').exists()
println new File('docs').exists()
println new File('/docs').exists()</syntaxhighlight>
println new File('/docs').exists()</syntaxhighlight>

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


<syntaxhighlight lang=haskell>import System.Directory (doesFileExist, doesDirectoryExist)
<syntaxhighlight lang="haskell">import System.Directory (doesFileExist, doesDirectoryExist)


check :: (FilePath -> IO Bool) -> FilePath -> IO ()
check :: (FilePath -> IO Bool) -> FilePath -> IO ()
Line 1,580: Line 1,530:
check doesFileExist "/input.txt"
check doesFileExist "/input.txt"
check doesDirectoryExist "/docs"</syntaxhighlight>
check doesDirectoryExist "/docs"</syntaxhighlight>

=={{header|hexiscript}}==
=={{header|hexiscript}}==
<syntaxhighlight lang=hexiscript>println "File \"input.txt\"? " + (exists "input.txt")
<syntaxhighlight lang="hexiscript">println "File \"input.txt\"? " + (exists "input.txt")
println "Dir \"docs\"? " + (exists "docs/")
println "Dir \"docs\"? " + (exists "docs/")
println "File \"/input.txt\"? " + (exists "/input.txt")
println "File \"/input.txt\"? " + (exists "/input.txt")
println "Dir \"/docs\"? " + (exists "/docs/")</syntaxhighlight>
println "Dir \"/docs\"? " + (exists "/docs/")</syntaxhighlight>

=={{header|HicEst}}==
=={{header|HicEst}}==
<syntaxhighlight lang=hicest> OPEN(FIle= 'input.txt', OLD, IOStat=ios, ERror=99)
<syntaxhighlight lang="hicest"> OPEN(FIle= 'input.txt', OLD, IOStat=ios, ERror=99)
OPEN(FIle='C:\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>
99 WRITE(Messagebox='!') 'File does not exist. Error message ', ios </syntaxhighlight>

=={{header|HolyC}}==
=={{header|HolyC}}==
<syntaxhighlight lang=holyc>U0 FileExists(U8 *f) {
<syntaxhighlight lang="holyc">U0 FileExists(U8 *f) {
if (FileFind(f) && !IsDir(f)) {
if (FileFind(f) && !IsDir(f)) {
Print("'%s' file exists.\n", f);
Print("'%s' file exists.\n", f);
Line 1,614: Line 1,561:
DirExists("docs");
DirExists("docs");
DirExists("::/docs");</syntaxhighlight>
DirExists("::/docs");</syntaxhighlight>

=={{header|i}}==
=={{header|i}}==
<syntaxhighlight lang=i>concept exists(path) {
<syntaxhighlight lang="i">concept exists(path) {
open(path)
open(path)
errors {
errors {
Line 1,634: Line 1,580:
exists("docs/Abdu'l-Bahá.txt")
exists("docs/Abdu'l-Bahá.txt")
}</syntaxhighlight>
}</syntaxhighlight>

=={{header|Icon}} and {{header|Unicon}}==
=={{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.
Icon doesn't support 'stat'; however, information can be obtained by use of the system function to access command line.
<syntaxhighlight lang=Unicon>every dir := !["./","/"] do {
<syntaxhighlight lang="unicon">every dir := !["./","/"] do {
write("file ", f := dir || "input.txt", if stat(f) then " exists." else " doesn't exist.")
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.")
write("directory ", f := dir || "docs", if stat(f) then " exists." else " doesn't exist.")
}</syntaxhighlight>
}</syntaxhighlight>
Note: Icon and Unicon accept both / and \ for directory separators.
Note: Icon and Unicon accept both / and \ for directory separators.

=={{header|IDL}}==
=={{header|IDL}}==
<syntaxhighlight lang=idl>
<syntaxhighlight lang="idl">
print, FILE_TEST('input.txt')
print, FILE_TEST('input.txt')
print, FILE_TEST(PATH_SEP()+'input.txt')
print, FILE_TEST(PATH_SEP()+'input.txt')
Line 1,651: Line 1,595:


</syntaxhighlight>
</syntaxhighlight>

=={{header|J}}==
=={{header|J}}==
<syntaxhighlight lang=j>require 'files'
<syntaxhighlight lang="j">require 'files'
fexist 'input.txt'
fexist 'input.txt'
fexist '/input.txt'
fexist '/input.txt'
Line 1,659: Line 1,602:
direxist 'docs'
direxist 'docs'
direxist '/docs'</syntaxhighlight>
direxist '/docs'</syntaxhighlight>

=={{header|Java}}==
=={{header|Java}}==
<syntaxhighlight lang=java>import java.io.File;
<syntaxhighlight lang="java">import java.io.File;
public class FileExistsTest {
public class FileExistsTest {
public static boolean isFileExists(String filename) {
public static boolean isFileExists(String filename) {
Line 1,680: Line 1,622:
}</syntaxhighlight>
}</syntaxhighlight>
{{works with|Java|7+}}
{{works with|Java|7+}}
<syntaxhighlight lang=java5>import java.nio.file.FileSystem;
<syntaxhighlight lang="java5">import java.nio.file.FileSystem;
import java.nio.file.FileSystems;
import java.nio.file.FileSystems;
import java.nio.file.Files;
import java.nio.file.Files;
Line 1,700: Line 1,642:
}
}
}</syntaxhighlight>
}</syntaxhighlight>

=={{header|JavaScript}}==
=={{header|JavaScript}}==
Javascript interpreters are now widely embedded in contexts which do have access to file systems, but the early context of browser scripting has precluded the inclusion of file system libraries in the definition of the language itself.
Javascript interpreters are now widely embedded in contexts which do have access to file systems, but the early context of browser scripting has precluded the inclusion of file system libraries in the definition of the language itself.
Each non-browser JS context is likely to have its own home-grown and unstandardised file system library.
Each non-browser JS context is likely to have its own home-grown and unstandardised file system library.
===JScript===
===JScript===
<syntaxhighlight lang=javascript>var fso = new ActiveXObject("Scripting.FileSystemObject");
<syntaxhighlight lang="javascript">var fso = new ActiveXObject("Scripting.FileSystemObject");


fso.FileExists('input.txt');
fso.FileExists('input.txt');
Line 1,716: Line 1,657:
{{Trans|Haskell}}
{{Trans|Haskell}}
(Adopting function names used in the Haskell System.Directory library)
(Adopting function names used in the Haskell System.Directory library)
<syntaxhighlight lang=JavaScript>(() => {
<syntaxhighlight lang="javascript">(() => {


// SYSTEM DIRECTORY FUNCTIONS
// SYSTEM DIRECTORY FUNCTIONS
Line 1,804: Line 1,745:
true
true
]</pre>
]</pre>

=={{header|Julia}}==
=={{header|Julia}}==
{{works with|Julia|0.6}}
{{works with|Julia|0.6}}


<syntaxhighlight lang=julia>@show isfile("input.txt")
<syntaxhighlight lang="julia">@show isfile("input.txt")
@show isfile("/input.txt")
@show isfile("/input.txt")
@show isdir("docs")
@show isdir("docs")
Line 1,814: Line 1,754:
@show isfile("")
@show isfile("")
@show isfile("`Abdu'l-Bahá.txt")</syntaxhighlight>
@show isfile("`Abdu'l-Bahá.txt")</syntaxhighlight>

=={{header|Klingphix}}==
=={{header|Klingphix}}==
<syntaxhighlight lang=Klingphix>include ..\Utilitys.tlhy
<syntaxhighlight lang="klingphix">include ..\Utilitys.tlhy


"foo.bar" "w" fopen
"foo.bar" "w" fopen
Line 1,828: Line 1,767:
{{out}}
{{out}}
<pre>Could not open 'fou.bar' for reading</pre>
<pre>Could not open 'fou.bar' for reading</pre>

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


import java.io.File
import java.io.File
Line 1,846: Line 1,784:
}
}
}</syntaxhighlight>
}</syntaxhighlight>

=={{header|LabVIEW}}==
=={{header|LabVIEW}}==
{{libheader|LabVIEW CWD}}
{{libheader|LabVIEW CWD}}
{{VI snippet}}<br/>
{{VI snippet}}<br/>
[[File:Ensure_that_a_file_exists.png]]
[[File:Ensure_that_a_file_exists.png]]

=={{header|Lasso}}==
=={{header|Lasso}}==
<syntaxhighlight lang=Lasso>// local file
<syntaxhighlight lang="lasso">// local file
file_exists('input.txt')
file_exists('input.txt')


Line 1,864: Line 1,800:
// directory in root file system (requires permissions at user OS level)
// directory in root file system (requires permissions at user OS level)
file_exists('//docs')</syntaxhighlight>
file_exists('//docs')</syntaxhighlight>

=={{header|LFE}}==
=={{header|LFE}}==
From the LFE REPL:
From the LFE REPL:
<syntaxhighlight lang=lisp>
<syntaxhighlight lang="lisp">
> (: filelib is_regular '"input.txt")
> (: filelib is_regular '"input.txt")
false
false
Line 1,877: Line 1,812:
false
false
</syntaxhighlight>
</syntaxhighlight>

=={{header|Liberty BASIC}}==
=={{header|Liberty BASIC}}==
<syntaxhighlight lang=lb>'fileExists.bas - Show how to determine if a file exists
<syntaxhighlight lang="lb">'fileExists.bas - Show how to determine if a file exists
dim info$(10,10)
dim info$(10,10)
input "Type a file path (ie. c:\windows\somefile.txt)?"; fpath$
input "Type a file path (ie. c:\windows\somefile.txt)?"; fpath$
Line 1,908: Line 1,842:
filenameOnly$ = right$(fullPath$, len(fullPath$)-pathLength)
filenameOnly$ = right$(fullPath$, len(fullPath$)-pathLength)
end function</syntaxhighlight>
end function</syntaxhighlight>

=={{header|Little}}==
=={{header|Little}}==
<syntaxhighlight lang=C>if (exists("input.txt")) {
<syntaxhighlight lang="c">if (exists("input.txt")) {
puts("The file \"input.txt\" exist");
puts("The file \"input.txt\" exist");
}
}
Line 1,922: Line 1,855:
puts("The file \"/docs\" exist");
puts("The file \"/docs\" exist");
}</syntaxhighlight>
}</syntaxhighlight>

=={{header|LiveCode}}==
=={{header|LiveCode}}==
<syntaxhighlight lang=LiveCode>there is a file "/input.txt"
<syntaxhighlight lang="livecode">there is a file "/input.txt"
there is a file "input.txt"
there is a file "input.txt"
there is a folder "docs"
there is a folder "docs"
there is a file "/docs/input.txt"</syntaxhighlight>
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
LiveCode also allows setting a default folder for subsequent file commands. To check if a file exists in the doc folder
<syntaxhighlight lang=LiveCode>set the defaultFolder to "docs"
<syntaxhighlight lang="livecode">set the defaultFolder to "docs"
there is a file "input.txt"</syntaxhighlight>
there is a file "input.txt"</syntaxhighlight>

=={{header|Logo}}==
=={{header|Logo}}==
{{works with|UCB Logo}}
{{works with|UCB Logo}}
<syntaxhighlight lang=logo>show file? "input.txt
<syntaxhighlight lang="logo">show file? "input.txt
show file? "/input.txt
show file? "/input.txt
show file? "docs
show file? "docs
show file? "/docs</syntaxhighlight>
show file? "/docs</syntaxhighlight>
Alternatively, one can set a file prefix used for subsequent file commands.
Alternatively, one can set a file prefix used for subsequent file commands.
<syntaxhighlight lang=logo>setprefix "/
<syntaxhighlight lang="logo">setprefix "/
show file? "input.txt</syntaxhighlight>
show file? "input.txt</syntaxhighlight>

=={{header|Lua}}==
=={{header|Lua}}==
For directories, the following only works on platforms on which directories can be opened for reading like files.
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 )
<syntaxhighlight lang="lua">function output( s, b )
if b then
if b then
print ( s, " does not exist." )
print ( s, " does not exist." )
Line 1,958: Line 1,888:


The following more portable solution uses LuaFileSystem.
The following more portable solution uses LuaFileSystem.
<syntaxhighlight lang=lua>require "lfs"
<syntaxhighlight lang="lua">require "lfs"
for i, path in ipairs({"input.txt", "/input.txt", "docs", "/docs"}) do
for i, path in ipairs({"input.txt", "/input.txt", "docs", "/docs"}) do
local mode = lfs.attributes(path, "mode")
local mode = lfs.attributes(path, "mode")
Line 1,967: Line 1,897:
end
end
end</syntaxhighlight>
end</syntaxhighlight>

=={{header|M2000 Interpreter}}==
=={{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.
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 Interpreter>
<syntaxhighlight lang="m2000 interpreter">
Module ExistDirAndFile {
Module ExistDirAndFile {
Let WorkingDir$=Dir$, RootDir$="C:\"
Let WorkingDir$=Dir$, RootDir$="C:\"
Line 1,991: Line 1,920:
ExistDirAndFile
ExistDirAndFile
</syntaxhighlight>
</syntaxhighlight>

=={{header|Maple}}==
=={{header|Maple}}==
<syntaxhighlight lang=Maple>with(FileTools):
<syntaxhighlight lang="maple">with(FileTools):
Exists("input.txt");
Exists("input.txt");
Exists("docs") and IsDirectory("docs");
Exists("docs") and IsDirectory("docs");
Exists("/input.txt");
Exists("/input.txt");
Exists("/docs") and IsDirectory("/docs");</syntaxhighlight>
Exists("/docs") and IsDirectory("/docs");</syntaxhighlight>

=={{header|Mathematica}} / {{header|Wolfram Language}}==
=={{header|Mathematica}} / {{header|Wolfram Language}}==
<syntaxhighlight lang=Mathematica>wd = NotebookDirectory[];
<syntaxhighlight lang="mathematica">wd = NotebookDirectory[];
FileExistsQ[wd <> "input.txt"]
FileExistsQ[wd <> "input.txt"]
DirectoryQ[wd <> "docs"]
DirectoryQ[wd <> "docs"]
Line 2,006: Line 1,933:
FileExistsQ["/" <> "input.txt"]
FileExistsQ["/" <> "input.txt"]
DirectoryQ["/" <> "docs"]</syntaxhighlight>
DirectoryQ["/" <> "docs"]</syntaxhighlight>

=={{header|MATLAB}} / {{header|Octave}}==
=={{header|MATLAB}} / {{header|Octave}}==
<syntaxhighlight lang=Matlab> exist('input.txt','file')
<syntaxhighlight lang="matlab"> exist('input.txt','file')
exist('/input.txt','file')
exist('/input.txt','file')
exist('docs','dir')
exist('docs','dir')
exist('/docs','dir')</syntaxhighlight>
exist('/docs','dir')</syntaxhighlight>

=={{header|MAXScript}}==
=={{header|MAXScript}}==
<syntaxhighlight lang=maxscript>-- Here
<syntaxhighlight lang="maxscript">-- Here
doesFileExist "input.txt"
doesFileExist "input.txt"
(getDirectories "docs").count == 1
(getDirectories "docs").count == 1
Line 2,020: Line 1,945:
doesFileExist "\input.txt"
doesFileExist "\input.txt"
(getDirectories "C:\docs").count == 1</syntaxhighlight>
(getDirectories "C:\docs").count == 1</syntaxhighlight>

=={{header|Modula-3}}==
=={{header|Modula-3}}==
<syntaxhighlight lang=modula3>MODULE FileTest EXPORTS Main;
<syntaxhighlight lang="modula3">MODULE FileTest EXPORTS Main;


IMPORT IO, Fmt, FS, File, OSError, Pathname;
IMPORT IO, Fmt, FS, File, OSError, Pathname;
Line 2,043: Line 1,967:
IO.Put(Fmt.Bool(FileExists("/docs")) & "\n");
IO.Put(Fmt.Bool(FileExists("/docs")) & "\n");
END FileTest.</syntaxhighlight>
END FileTest.</syntaxhighlight>

=={{header|Nanoquery}}==
=={{header|Nanoquery}}==
<syntaxhighlight lang=Nanoquery>import Nanoquery.IO
<syntaxhighlight lang="nanoquery">import Nanoquery.IO


def exists(fname)
def exists(fname)
Line 2,052: Line 1,975:
return f.exists()
return f.exists()
end</syntaxhighlight>
end</syntaxhighlight>

=={{header|Neko}}==
=={{header|Neko}}==
<syntaxhighlight lang=ActionScript>/**
<syntaxhighlight lang="actionscript">/**
Check that file/dir exists, in Neko
Check that file/dir exists, in Neko
*/
*/
Line 2,091: Line 2,013:
empty.txt exists as empty file: true
empty.txt exists as empty file: true
`Abdu'l-Bahá.txt exists as file: true</pre>
`Abdu'l-Bahá.txt exists as file: true</pre>

=={{header|Nemerle}}==
=={{header|Nemerle}}==
{{trans|C#}}
{{trans|C#}}
<syntaxhighlight lang=Nemerle>using System.Console;
<syntaxhighlight lang="nemerle">using System.Console;
using System.IO;
using System.IO;
Line 2,101: Line 2,022:
WriteLine(Directory.Exists("docs"));
WriteLine(Directory.Exists("docs"));
WriteLine(Directory.Exists("/docs"));</syntaxhighlight>
WriteLine(Directory.Exists("/docs"));</syntaxhighlight>

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


Line 2,148: Line 2,068:
return
return
</syntaxhighlight>
</syntaxhighlight>

=={{header|NewLISP}}==
=={{header|NewLISP}}==
<syntaxhighlight lang=NewLISP>(dolist (file '("input.txt" "/input.txt"))
<syntaxhighlight lang="newlisp">(dolist (file '("input.txt" "/input.txt"))
(if (file? file true)
(if (file? file true)
(println "file " file " exists")))
(println "file " file " exists")))
Line 2,157: Line 2,076:
(if (directory? dir)
(if (directory? dir)
(println "directory " dir " exists")))</syntaxhighlight>
(println "directory " dir " exists")))</syntaxhighlight>

=={{header|Nim}}==
=={{header|Nim}}==
<syntaxhighlight lang=nim>import os
<syntaxhighlight lang="nim">import os


echo fileExists "input.txt"
echo fileExists "input.txt"
Line 2,165: Line 2,083:
echo dirExists "docs"
echo dirExists "docs"
echo dirExists "/docs"</syntaxhighlight>
echo dirExists "/docs"</syntaxhighlight>

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


Line 2,180: Line 2,097:
}
}
</syntaxhighlight>
</syntaxhighlight>

=={{header|Objective-C}}==
=={{header|Objective-C}}==
<syntaxhighlight lang=objc>NSFileManager *fm = [NSFileManager defaultManager];
<syntaxhighlight lang="objc">NSFileManager *fm = [NSFileManager defaultManager];
NSLog(@"input.txt %s", [fm fileExistsAtPath:@"input.txt"] ? @"exists" : @"doesn't exist");
NSLog(@"input.txt %s", [fm fileExistsAtPath:@"input.txt"] ? @"exists" : @"doesn't exist");
NSLog(@"docs %s", [fm fileExistsAtPath:@"docs"] ? @"exists" : @"doesn't exist");</syntaxhighlight>
NSLog(@"docs %s", [fm fileExistsAtPath:@"docs"] ? @"exists" : @"doesn't exist");</syntaxhighlight>

=={{header|OCaml}}==
=={{header|OCaml}}==
<syntaxhighlight lang=ocaml>Sys.file_exists "input.txt";;
<syntaxhighlight lang="ocaml">Sys.file_exists "input.txt";;
Sys.file_exists "docs";;
Sys.file_exists "docs";;
Sys.file_exists "/input.txt";;
Sys.file_exists "/input.txt";;
Sys.file_exists "/docs";;</syntaxhighlight>
Sys.file_exists "/docs";;</syntaxhighlight>

=={{header|ooRexx}}==
=={{header|ooRexx}}==
<syntaxhighlight lang=oorexx>/**********************************************************************
<syntaxhighlight lang="oorexx">/**********************************************************************
* exists(filespec)
* exists(filespec)
* returns 1 if filespec identifies a file with size>0
* returns 1 if filespec identifies a file with size>0
Line 2,213: Line 2,127:
If size=0 Then Say spec 'is a zero-size file'
If size=0 Then Say spec 'is a zero-size file'
Return 0</syntaxhighlight>
Return 0</syntaxhighlight>

=={{header|Oz}}==
=={{header|Oz}}==
<syntaxhighlight lang=oz>declare
<syntaxhighlight lang="oz">declare
[Path] = {Module.link ['x-oz://system/os/Path.ozf']}
[Path] = {Module.link ['x-oz://system/os/Path.ozf']}
in
in
Line 2,222: Line 2,135:
{Show {Path.exists "/docs"}}
{Show {Path.exists "/docs"}}
{Show {Path.exists "/input.txt"}}</syntaxhighlight>
{Show {Path.exists "/input.txt"}}</syntaxhighlight>

=={{header|PARI/GP}}==
=={{header|PARI/GP}}==
<syntaxhighlight lang=parigp>trap(,"does not exist",read("input.txt");"exists")
<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:\\input.txt");"exists")
trap(,"does not exist",read("c:\\dirname\\nul");"exists")</syntaxhighlight>
trap(,"does not exist",read("c:\\dirname\\nul");"exists")</syntaxhighlight>
Line 2,231: Line 2,143:


Under PARI it would typically be more convenient to use [[#C|C]] methods.
Under PARI it would typically be more convenient to use [[#C|C]] methods.

=={{header|Pascal}}==
=={{header|Pascal}}==
See [[Ensure_that_a_file_exists#Delphi | Delphi]]
See [[Ensure_that_a_file_exists#Delphi | Delphi]]

=={{header|Perl}}==
=={{header|Perl}}==
<syntaxhighlight lang=perl>use File::Spec::Functions qw(catfile rootdir);
<syntaxhighlight lang="perl">use File::Spec::Functions qw(catfile rootdir);
# here
# here
print -e 'input.txt';
print -e 'input.txt';
Line 2,251: Line 2,161:
perl -e 'print -e "/input.txt", "\n";'
perl -e 'print -e "/input.txt", "\n";'
perl -e 'print -d "/docs", "\n";'
perl -e 'print -d "/docs", "\n";'

=={{header|Phix}}==
=={{header|Phix}}==
{{libheader|Phix/basics}}
{{libheader|Phix/basics}}
<!--<syntaxhighlight lang=Phix>(notonline)-->
<!--<syntaxhighlight lang="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;">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>
<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: Line 2,189:
directory /Program Files (x86) exists.
directory /Program Files (x86) exists.
</pre>
</pre>

=={{header|Phixmonti}}==
=={{header|Phixmonti}}==
<syntaxhighlight lang=Phixmonti>"foo.bar" "w" fopen
<syntaxhighlight lang="phixmonti">"foo.bar" "w" fopen
"Hallo !" over fputs
"Hallo !" over fputs
fclose
fclose
Line 2,288: Line 2,196:
"fou.bar" "r" fopen
"fou.bar" "r" fopen
dup 0 < if "Could not open 'foo.bar' for reading" print drop else fclose endif</syntaxhighlight>
dup 0 < if "Could not open 'foo.bar' for reading" print drop else fclose endif</syntaxhighlight>

=={{header|PHP}}==
=={{header|PHP}}==
<syntaxhighlight lang=php>if (file_exists('input.txt')) echo 'input.txt is here right by my side';
<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('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('/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>
if (file_exists('/docs' )) echo 'docs is over there in the root dir';</syntaxhighlight>

=={{header|PicoLisp}}==
=={{header|PicoLisp}}==
<syntaxhighlight lang=PicoLisp>(if (info "file.txt")
<syntaxhighlight lang="picolisp">(if (info "file.txt")
(prinl "Size: " (car @) " bytes, last modified " (stamp (cadr @) (cddr @)))
(prinl "Size: " (car @) " bytes, last modified " (stamp (cadr @) (cddr @)))
(prinl "File doesn't exist") )
(prinl "File doesn't exist") )
Line 2,317: Line 2,223:
(NIL "Directory exists") ) ) )
(NIL "Directory exists") ) ) )
</syntaxhighlight>
</syntaxhighlight>

=={{header|Pike}}==
=={{header|Pike}}==
<syntaxhighlight lang=pike>import Stdio;
<syntaxhighlight lang="pike">import Stdio;


int main(){
int main(){
Line 2,330: Line 2,235:
}
}
}</syntaxhighlight>
}</syntaxhighlight>

=={{header|PL/I}}==
=={{header|PL/I}}==
<syntaxhighlight lang=pli>*Process source or(!);
<syntaxhighlight lang="pli">*Process source or(!);
/*********************************************************************
/*********************************************************************
* 20.10.2013 Walter Pachl
* 20.10.2013 Walter Pachl
Line 2,359: Line 2,263:
File D:\_l\nix.txt not found
File D:\_l\nix.txt not found
</pre>
</pre>

=={{header|PL/M}}==
=={{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.
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: Line 2,268:
<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>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.
<br>CP/M filenames are up to 8 characters long with an optional, up to three character extension.
<syntaxhighlight lang=plm>100H:
<syntaxhighlight lang="plm">100H:


DECLARE FCB$SIZE LITERALLY '36';
DECLARE FCB$SIZE LITERALLY '36';
Line 2,461: Line 2,364:
Bdos Err on A: Select
Bdos Err on A: Select
</pre>
</pre>

=={{header|Pop11}}==
=={{header|Pop11}}==


<syntaxhighlight lang=pop11>sys_file_exists('input.txt') =>
<syntaxhighlight lang="pop11">sys_file_exists('input.txt') =>
sys_file_exists('/input.txt') =>
sys_file_exists('/input.txt') =>
sys_file_exists('docs') =>
sys_file_exists('docs') =>
Line 2,473: Line 2,375:
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:
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
<syntaxhighlight lang="pop11">;;; Define an auxilary function, returns boolean
define file_readable(fname);
define file_readable(fname);
lvars f = sysopen(fname, 0, true, `A`);
lvars f = sysopen(fname, 0, true, `A`);
Line 2,494: Line 2,396:


Users can easily define special cases of the general procedure.
Users can easily define special cases of the general procedure.

=={{header|PowerShell}}==
=={{header|PowerShell}}==


<syntaxhighlight lang=powershell> if (Test-Path -Path .\input.txt) {
<syntaxhighlight lang="powershell"> if (Test-Path -Path .\input.txt) {
write-host "File input exist"
write-host "File input exist"
}
}
Line 2,503: Line 2,404:
write-host "File input doesn't exist"
write-host "File input doesn't exist"
}</syntaxhighlight>
}</syntaxhighlight>

=={{header|Prolog}}==
=={{header|Prolog}}==


{{works with|SWI-Prolog|6.6}}
{{works with|SWI-Prolog|6.6}}


<syntaxhighlight lang=prolog>
<syntaxhighlight lang="prolog">


exists_file('input.txt'),
exists_file('input.txt'),
Line 2,517: Line 2,417:


</syntaxhighlight>
</syntaxhighlight>

=={{header|PureBasic}}==
=={{header|PureBasic}}==
<syntaxhighlight lang=PureBasic>result = ReadFile(#PB_Any, "input.txt")
<syntaxhighlight lang="purebasic">result = ReadFile(#PB_Any, "input.txt")
If result>0 : Debug "this local file exists"
If result>0 : Debug "this local file exists"
Else : Debug "result=" +Str(result) +" so this local file is missing"
Else : Debug "result=" +Str(result) +" so this local file is missing"
Line 2,538: Line 2,437:
Else : Debug "result=" +Str(result) +" so this root directory is missing"
Else : Debug "result=" +Str(result) +" so this root directory is missing"
EndIf </syntaxhighlight>
EndIf </syntaxhighlight>

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


<syntaxhighlight lang=python>import os
<syntaxhighlight lang="python">import os


os.path.isfile("input.txt")
os.path.isfile("input.txt")
Line 2,549: Line 2,447:


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.
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}}==
=={{header|QB64}}==
<syntaxhighlight lang=qbasic>$NOPREFIX
<syntaxhighlight lang="qbasic">$NOPREFIX
PRINT DIREXISTS("docs")
PRINT DIREXISTS("docs")
PRINT DIREXISTS("\docs")
PRINT DIREXISTS("\docs")
PRINT FILEEXISTS("input.txt")
PRINT FILEEXISTS("input.txt")
PRINT FILEEXISTS("\input.txt")</syntaxhighlight>
PRINT FILEEXISTS("\input.txt")</syntaxhighlight>

=={{header|R}}==
=={{header|R}}==
<syntaxhighlight lang=R>file.exists("input.txt")
<syntaxhighlight lang="r">file.exists("input.txt")
file.exists("/input.txt")
file.exists("/input.txt")
file.exists("docs")
file.exists("docs")
Line 2,570: Line 2,466:
This works with special names:
This works with special names:


<syntaxhighlight lang=R>file.exists("`Abdu'l-Bahá.txt")</syntaxhighlight>
<syntaxhighlight lang="r">file.exists("`Abdu'l-Bahá.txt")</syntaxhighlight>

=={{header|Racket}}==
=={{header|Racket}}==


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


Line 2,590: Line 2,485:
(file-exists? "docs")))
(file-exists? "docs")))
</syntaxhighlight>
</syntaxhighlight>

=={{header|Raku}}==
=={{header|Raku}}==
(formerly Perl 6)
(formerly Perl 6)
<syntaxhighlight lang=raku line>
<syntaxhighlight lang="raku" line>
my $path = "/etc/passwd";
my $path = "/etc/passwd";
say $path.IO.e ?? "Exists" !! "Does not exist";
say $path.IO.e ?? "Exists" !! "Does not exist";
Line 2,606: Line 2,500:
<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.
<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>
<syntaxhighlight lang="raku" line>
run ('touch', "♥ Unicode.txt");
run ('touch', "♥ Unicode.txt");


Line 2,612: Line 2,506:
say "♥ Unicode.txt".IO ~~ :e; # same
say "♥ Unicode.txt".IO ~~ :e; # same
</syntaxhighlight>
</syntaxhighlight>

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


<syntaxhighlight lang=raven>'input.txt' exists if 'input.txt exists' print
<syntaxhighlight lang="raven">'input.txt' exists if 'input.txt exists' print
'/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
'/docs' isdir if '/docs exists and is a directory' print</syntaxhighlight>
'/docs' isdir if '/docs exists and is a directory' print</syntaxhighlight>

=={{header|REBOL}}==
=={{header|REBOL}}==
<syntaxhighlight lang=REBOL>exists? %input.txt
<syntaxhighlight lang="rebol">exists? %input.txt
exists? %docs/
exists? %docs/


exists? %/input.txt
exists? %/input.txt
exists? %/docs/</syntaxhighlight>
exists? %/docs/</syntaxhighlight>

=={{header|Red}}==
=={{header|Red}}==
<syntaxhighlight lang=Red>exists? %input.txt
<syntaxhighlight lang="red">exists? %input.txt
exists? %docs/
exists? %docs/
exists? %/c/input.txt
exists? %/c/input.txt
Line 2,637: Line 2,528:
>> exists? %`Abdu'l-Bahá.txt
>> exists? %`Abdu'l-Bahá.txt
== true</syntaxhighlight>
== true</syntaxhighlight>

=={{header|REXX}}==
=={{header|REXX}}==
===version 1===
===version 1===
Line 2,643: Line 2,533:
{{works with|Personal REXX}}
{{works with|Personal REXX}}
{{works with|Regina}}
{{works with|Regina}}
<syntaxhighlight lang=rexx>/*REXX program creates a new empty file and directory in current directory and root dir.*/
<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. */
fn= 'input.txt' /*default name of a file. */
dn= 'docs' /*default name of a directory (folder).*/
dn= 'docs' /*default name of a directory (folder).*/
Line 2,670: Line 2,560:
{{works with|ARexx}}
{{works with|ARexx}}
{{works with|Regina 3.8 and later, with options: &nbsp; AREXX_BIFS &nbsp; AREXX_SEMANTICS}}
{{works with|Regina 3.8 and later, with options: &nbsp; AREXX_BIFS &nbsp; AREXX_SEMANTICS}}
<syntaxhighlight lang=rexx>
<syntaxhighlight lang="rexx">
/* Check if a file already exists */
/* Check if a file already exists */
filename='file.txt'
filename='file.txt'
Line 2,680: Line 2,570:
RETURN 1
RETURN 1
</syntaxhighlight>
</syntaxhighlight>

=={{header|Ring}}==
=={{header|Ring}}==
<syntaxhighlight lang=ring>
<syntaxhighlight lang="ring">
aFile = "C:\Ring\ReadMe.txt"
aFile = "C:\Ring\ReadMe.txt"
see aFile
see aFile
Line 2,688: Line 2,577:
else see " doesn't exist" + nl ok
else see " doesn't exist" + nl ok
</syntaxhighlight>
</syntaxhighlight>

=={{header|RLaB}}==
=={{header|RLaB}}==


RLaB provides two user functions for the task, ''isfile'' and ''isdir''.
RLaB provides two user functions for the task, ''isfile'' and ''isdir''.
<syntaxhighlight lang=RLaB>
<syntaxhighlight lang="rlab">
>> isdir("docs")
>> isdir("docs")
0
0
Line 2,698: Line 2,586:
0
0
</syntaxhighlight>
</syntaxhighlight>

=={{header|Ruby}}==
=={{header|Ruby}}==
<code>File.exists?</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>.
<code>File.exists?</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")
<syntaxhighlight lang="ruby">File.file?("input.txt")
File.file?("/input.txt")
File.file?("/input.txt")
File.directory?("docs")
File.directory?("docs")
Line 2,709: Line 2,596:
The next program runs all four checks and prints the results.
The next program runs all four checks and prints the results.


<syntaxhighlight lang=ruby>["input.txt", "/input.txt"].each { |f|
<syntaxhighlight lang="ruby">["input.txt", "/input.txt"].each { |f|
printf "%s is a regular file? %s\n", f, File.file?(f) }
printf "%s is a regular file? %s\n", f, File.file?(f) }
["docs", "/docs"].each { |d|
["docs", "/docs"].each { |d|
printf "%s is a directory? %s\n", d, File.directory?(d) }</syntaxhighlight>
printf "%s is a directory? %s\n", d, File.directory?(d) }</syntaxhighlight>

=={{header|Run BASIC}}==
=={{header|Run BASIC}}==
<syntaxhighlight lang=runbasic>files #f,"input.txt"
<syntaxhighlight lang="runbasic">files #f,"input.txt"
if #f hasanswer() = 1 then print "File does not exist"
if #f hasanswer() = 1 then print "File does not exist"
files #f,"docs"
files #f,"docs"
Line 2,721: Line 2,607:
if #f isDir() = 0 then print "This is a directory"
if #f isDir() = 0 then print "This is a directory"
</syntaxhighlight>
</syntaxhighlight>

=={{header|Rust}}==
=={{header|Rust}}==
<syntaxhighlight lang=rust>use std::fs;
<syntaxhighlight lang="rust">use std::fs;


fn main() {
fn main() {
Line 2,742: Line 2,627:
}
}
</syntaxhighlight>
</syntaxhighlight>

=={{header|Scala}}==
=={{header|Scala}}==
{{libheader|Scala}}<syntaxhighlight lang=scala>import java.nio.file.{ Files, FileSystems }
{{libheader|Scala}}<syntaxhighlight lang="scala">import java.nio.file.{ Files, FileSystems }


object FileExistsTest extends App {
object FileExistsTest extends App {
Line 2,761: Line 2,645:
List("output.txt", separator + "output.txt", "docs", separator + "docs" + separator).foreach(test)
List("output.txt", separator + "output.txt", "docs", separator + "docs" + separator).foreach(test)
}</syntaxhighlight>
}</syntaxhighlight>

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

=={{header|Seed7}}==
=={{header|Seed7}}==


<syntaxhighlight lang=seed7>$ include "seed7_05.s7i";
<syntaxhighlight lang="seed7">$ include "seed7_05.s7i";


const proc: main is func
const proc: main is func
Line 2,777: Line 2,659:
writeln(fileType("/docs") = FILE_DIR);
writeln(fileType("/docs") = FILE_DIR);
end func;</syntaxhighlight>
end func;</syntaxhighlight>

=={{header|SenseTalk}}==
=={{header|SenseTalk}}==
<syntaxhighlight lang=sensetalk>
<syntaxhighlight lang="sensetalk">
put file "input.txt" exists
put file "input.txt" exists
put folder "docs" exists
put folder "docs" exists
Line 2,786: Line 2,667:
put there is a folder "/docs"
put there is a folder "/docs"
</syntaxhighlight>
</syntaxhighlight>

=={{header|Sidef}}==
=={{header|Sidef}}==
<syntaxhighlight lang=ruby># Here
<syntaxhighlight lang="ruby"># Here
say (Dir.cwd + %f'input.txt' -> is_file);
say (Dir.cwd + %f'input.txt' -> is_file);
say (Dir.cwd + %d'docs' -> is_dir);
say (Dir.cwd + %d'docs' -> is_dir);
Line 2,796: Line 2,676:
say (Dir.root + %d'docs' -> is_dir);</syntaxhighlight>
say (Dir.root + %d'docs' -> is_dir);</syntaxhighlight>
NOTE: To check only for existence, use the method ''exists''
NOTE: To check only for existence, use the method ''exists''

=={{header|Slate}}==
=={{header|Slate}}==
<syntaxhighlight lang=slate>(File newNamed: 'input.txt') exists
<syntaxhighlight lang="slate">(File newNamed: 'input.txt') exists
(File newNamed: '/input.txt') exists
(File newNamed: '/input.txt') exists
(Directory root / 'input.txt') exists
(Directory root / 'input.txt') exists
(Directory newNamed: 'docs') exists
(Directory newNamed: 'docs') exists
(Directory newNamed: '/docs') exists</syntaxhighlight>
(Directory newNamed: '/docs') exists</syntaxhighlight>

=={{header|Smalltalk}}==
=={{header|Smalltalk}}==


[[Squeak]] has no notion of 'current directory' because it isn't tied to the shell that created it.
[[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'.
<syntaxhighlight lang="smalltalk">FileDirectory new fileExists: 'c:\serial'.
(FileDirectory on: 'c:\') directoryExists: 'docs'.</syntaxhighlight>
(FileDirectory on: 'c:\') directoryExists: 'docs'.</syntaxhighlight>


In [[GNU Smalltalk]] instead you can do:
In [[GNU Smalltalk]] instead you can do:


<syntaxhighlight lang=smalltalk>(Directory name: 'docs') exists ifTrue: [ ... ]
<syntaxhighlight lang="smalltalk">(Directory name: 'docs') exists ifTrue: [ ... ]
(Directory name: 'c:\docs') exists ifTrue: [ ... ]
(Directory name: 'c:\docs') exists ifTrue: [ ... ]
(File name: 'serial') isFile ifTrue: [ ... ]
(File name: 'serial') isFile ifTrue: [ ... ]
Line 2,819: Line 2,697:


Using ''exists'' in the third and fourth case will return true for directories too.
Using ''exists'' in the third and fourth case will return true for directories too.

=={{header|Standard ML}}==
=={{header|Standard ML}}==
<syntaxhighlight lang=sml>OS.FileSys.access ("input.txt", []);
<syntaxhighlight lang="sml">OS.FileSys.access ("input.txt", []);
OS.FileSys.access ("docs", []);
OS.FileSys.access ("docs", []);
OS.FileSys.access ("/input.txt", []);
OS.FileSys.access ("/input.txt", []);
OS.FileSys.access ("/docs", []);</syntaxhighlight>
OS.FileSys.access ("/docs", []);</syntaxhighlight>

=={{header|Stata}}==
=={{header|Stata}}==
Mata has functions to check the existence of files and directories:
Mata has functions to check the existence of files and directories:
<syntaxhighlight lang=stata>mata
<syntaxhighlight lang="stata">mata
fileexists("input.txt")
fileexists("input.txt")
direxists("docs")
direxists("docs")
Line 2,835: Line 2,711:
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.
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
<syntaxhighlight lang="stata">capture confirm file input.txt
if !_rc {
if !_rc {
* do something if the file exists
* do something if the file exists
Line 2,842: Line 2,718:
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:
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
<syntaxhighlight lang="stata">confirmdir docs
if !`r(confirmdir)' {
if !`r(confirmdir)' {
* do something if the directory exists
* do something if the directory exists
Line 2,849: Line 2,725:
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:
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>
<syntaxhighlight lang="stata">confirm file "\`Abdu'l-Bahá.txt"</syntaxhighlight>

=={{header|Tcl}}==
=={{header|Tcl}}==
Taking the meaning of the task from the DOS example: <!-- multiline “if” because of formatting -->
Taking the meaning of the task from the DOS example: <!-- multiline “if” because of formatting -->
<syntaxhighlight lang=tcl>if { [file exists "input.txt"] } {
<syntaxhighlight lang="tcl">if { [file exists "input.txt"] } {
puts "input.txt exists"
puts "input.txt exists"
}
}
Line 2,869: Line 2,744:
}</syntaxhighlight>
}</syntaxhighlight>
Note that these operations do not require the use of <tt>file nativename</tt> on either Windows or any version of Unix.
Note that these operations do not require the use of <tt>file nativename</tt> on either Windows or any version of Unix.

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


<syntaxhighlight lang=toka>[ "R" file.open dup 0 <> [ dup file.close ] ifTrue 0 <> ] is exists?
<syntaxhighlight lang="toka">[ "R" file.open dup 0 <> [ dup file.close ] ifTrue 0 <> ] is exists?
" input.txt" exists? .
" input.txt" exists? .
" /input.txt" exists? .
" /input.txt" exists? .
" docs" exists? .
" docs" exists? .
" /docs" exists? .</syntaxhighlight>
" /docs" exists? .</syntaxhighlight>

=={{header|True BASIC}}==
=={{header|True BASIC}}==
<syntaxhighlight lang=truebasic>SUB opener (a$)
<syntaxhighlight lang="truebasic">SUB opener (a$)
WHEN EXCEPTION IN
WHEN EXCEPTION IN
OPEN #1: NAME f$
OPEN #1: NAME f$
Line 2,903: Line 2,776:
CALL opener (f$)
CALL opener (f$)
END</syntaxhighlight>
END</syntaxhighlight>

=={{header|TUSCRIPT}}==
=={{header|TUSCRIPT}}==
<syntaxhighlight lang=tuscript>
<syntaxhighlight lang="tuscript">
$$ MODE TUSCRIPT
$$ MODE TUSCRIPT
file="input.txt",directory="docs"
file="input.txt",directory="docs"
Line 2,924: Line 2,796:
@@@@@@@@ directory docs not exists @@@@@@@@
@@@@@@@@ directory docs not exists @@@@@@@@
</pre>
</pre>

=={{header|UNIX Shell}}==
=={{header|UNIX Shell}}==
<syntaxhighlight lang=bash>test -f input.txt
<syntaxhighlight lang="bash">test -f input.txt
test -f /input.txt
test -f /input.txt
test -d docs
test -d docs
Line 2,933: Line 2,804:
The next program runs all four checks and prints the results.
The next program runs all four checks and prints the results.


<syntaxhighlight lang=bash>for f in input.txt /input.txt; do
<syntaxhighlight lang="bash">for f in input.txt /input.txt; do
test -f "$f" && r=true || r=false
test -f "$f" && r=true || r=false
echo "$f is a regular file? $r"
echo "$f is a regular file? $r"
Line 2,941: Line 2,812:
echo "$d is a directory? $r"
echo "$d is a directory? $r"
done</syntaxhighlight>
done</syntaxhighlight>

=={{header|Ursa}}==
=={{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.
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)
<syntaxhighlight lang="ursa">def exists (string filename)
decl file f
decl file f
try
try
Line 2,953: Line 2,823:
end try
end try
end exists</syntaxhighlight>
end exists</syntaxhighlight>

=={{header|Vala}}==
=={{header|Vala}}==
This needs to be compiled with the gio-2.0 package: valac --pkg gio-2.0 check_that_file_exists.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) {
<syntaxhighlight lang="vala">int main (string[] args) {
string[] files = {"input.txt", "docs", Path.DIR_SEPARATOR_S + "input.txt", Path.DIR_SEPARATOR_S + "docs"};
string[] files = {"input.txt", "docs", Path.DIR_SEPARATOR_S + "input.txt", Path.DIR_SEPARATOR_S + "docs"};
foreach (string f in files) {
foreach (string f in files) {
Line 2,965: Line 2,834:
}</syntaxhighlight>
}</syntaxhighlight>
A more complete version which informs whether the existing file is a regular file or a directory
A more complete version which informs whether the existing file is a regular file or a directory
<syntaxhighlight lang=vala>int main (string[] args) {
<syntaxhighlight lang="vala">int main (string[] args) {
string[] files = {"input.txt", "docs", Path.DIR_SEPARATOR_S + "input.txt", Path.DIR_SEPARATOR_S + "docs"};
string[] files = {"input.txt", "docs", Path.DIR_SEPARATOR_S + "input.txt", Path.DIR_SEPARATOR_S + "docs"};
foreach (var f in files) {
foreach (var f in files) {
Line 2,985: Line 2,854:
return 0;
return 0;
}</syntaxhighlight>
}</syntaxhighlight>

=={{header|VBA}}==
=={{header|VBA}}==


<syntaxhighlight lang=vb>
<syntaxhighlight lang="vb">
Option Explicit
Option Explicit


Line 3,008: Line 2,876:
End Function
End Function
</syntaxhighlight>
</syntaxhighlight>

=={{header|VBScript}}==
=={{header|VBScript}}==


<syntaxhighlight lang=vbscript>Set FSO = CreateObject("Scripting.FileSystemObject")
<syntaxhighlight lang="vbscript">Set FSO = CreateObject("Scripting.FileSystemObject")


Function FileExists(strFile)
Function FileExists(strFile)
Line 3,047: Line 2,914:


</syntaxhighlight>
</syntaxhighlight>

=={{header|Vedit macro language}}==
=={{header|Vedit macro language}}==
Vedit allows using either '\' or '/' as directory separator character, it is automatically converted to the one used by the operating system.
Vedit allows using either '\' or '/' as directory separator character, it is automatically converted to the one used by the operating system.
<syntaxhighlight lang=vedit>// In current directory
<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("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") }
if (File_Exist("docs/nul", NOERR)) { M("docs exists\n") } else { M("docs does not exist\n") }
Line 3,057: Line 2,923:
if (File_Exist("/input.txt")) { M("/input.txt exists\n") } else { M("/input.txt does not exist\n") }
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>
if (File_Exist("/docs/nul", NOERR)) { M("/docs exists\n") } else { M("/docs does not exist\n") }</syntaxhighlight>

=={{header|Visual Basic}}==
=={{header|Visual Basic}}==
{{works with|Visual Basic|VB6 Standard}}
{{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:
The proposed solutions for VBA and VBScript work in VB6 as well, however here's a Windows API based approach:
<syntaxhighlight lang=vb>
<syntaxhighlight lang="vb">
'declarations:
'declarations:
Public Declare Function GetFileAttributes Lib "kernel32" _
Public Declare Function GetFileAttributes Lib "kernel32" _
Line 3,079: Line 2,944:
End Function
End Function
</syntaxhighlight>
</syntaxhighlight>

=={{header|Visual Basic .NET}}==
=={{header|Visual Basic .NET}}==
'''Platform:''' [[.NET]]
'''Platform:''' [[.NET]]


{{works with|Visual Basic .NET|9.0+}}
{{works with|Visual Basic .NET|9.0+}}
<syntaxhighlight lang=vbnet>'Current Directory
<syntaxhighlight lang="vbnet">'Current Directory
Console.WriteLine(If(IO.Directory.Exists("docs"), "directory exists", "directory doesn't exists"))
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"))
Console.WriteLine(If(IO.Directory.Exists("output.txt"), "file exists", "file doesn't exists"))
Line 3,097: Line 2,961:
Console.WriteLine(If(IO.Directory.Exists(IO.Path.DirectorySeparatorChar & "output.txt"), _
Console.WriteLine(If(IO.Directory.Exists(IO.Path.DirectorySeparatorChar & "output.txt"), _
"file exists", "file doesn't exists"))</syntaxhighlight>
"file exists", "file doesn't exists"))</syntaxhighlight>

=={{header|Vlang}}==
=={{header|Vlang}}==
<syntaxhighlight lang=go>// Check file exists in V
<syntaxhighlight lang="go">// Check file exists in V
// Tectonics: v run check-that-file-exists.v
// Tectonics: v run check-that-file-exists.v
module main
module main
Line 3,137: Line 3,000:
os.is_file('empty.txt'): true
os.is_file('empty.txt'): true
os.is_file("`Abdu'l-Bahá.txt"): true</pre>
os.is_file("`Abdu'l-Bahá.txt"): true</pre>


=={{header|Wren}}==
=={{header|Wren}}==
Empty files and directories have been created beforehand.
Empty files and directories have been created beforehand.
Line 3,145: Line 3,006:


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.
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>import "io" for Directory, File
<syntaxhighlight lang="ecmascript">import "io" for Directory, File


for (name in ["input.txt", "`Abdu'l-Bahá.txt"]) {
for (name in ["input.txt", "`Abdu'l-Bahá.txt"]) {
Line 3,170: Line 3,031:
docs directory exists and contains 0 files.
docs directory exists and contains 0 files.
</pre>
</pre>

=={{header|XPL0}}==
=={{header|XPL0}}==
Attempting to open a non-existent file or directory will cause an error.
Attempting to open a non-existent file or directory will cause an error.
A zero-length file is detected as existing.
A zero-length file is detected as existing.
<syntaxhighlight lang=XPL0>
<syntaxhighlight lang="xpl0">
int FD; \file descriptor
int FD; \file descriptor
[Trap(false); \prevent errors from aborting program
[Trap(false); \prevent errors from aborting program
Line 3,186: Line 3,046:
if GetErr then Text(0, "/dir doesn't exist^m^j");
if GetErr then Text(0, "/dir doesn't exist^m^j");
]</syntaxhighlight>
]</syntaxhighlight>

=={{header|Yabasic}}==
=={{header|Yabasic}}==
<syntaxhighlight lang=Yabasic>open "foo.bar" for writing as #1
<syntaxhighlight lang="yabasic">open "foo.bar" for writing as #1
print #1 "Hallo !"
print #1 "Hallo !"
close #1
close #1
Line 3,195: Line 3,054:
if (not open(1,"buzz.bar")) print "Could not open 'buzz.bar' for reading"
if (not open(1,"buzz.bar")) print "Could not open 'buzz.bar' for reading"
</syntaxhighlight>
</syntaxhighlight>

=={{header|zkl}}==
=={{header|zkl}}==
<syntaxhighlight lang=zkl>File.exists("input.txt") //--> True (in this case a sym link)
<syntaxhighlight lang="zkl">File.exists("input.txt") //--> True (in this case a sym link)
File.exists("/input.txt") //-->False
File.exists("/input.txt") //-->False
File.isDir("/") //-->True
File.isDir("/") //-->True
File.isDir("docs") //-->False
File.isDir("docs") //-->False
</syntaxhighlight>
</syntaxhighlight>

{{omit from|Befunge|No filesystem support}}
{{omit from|Befunge|No filesystem support}}
{{omit from|HTML}}
{{omit from|HTML}}