In this task, the job is to verify that a file called "input.txt" and the directory called "docs" exist. This should be done twice: once for the current working directory and once for a file and a directory in the filesystem root.

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

Optional criteria (May 2015): verify it works with 0-length files; and with an unusual filename: `Abdu'l-Bahá.txt

Ada

This example should work with any Ada 95 compiler. <lang ada>with Ada.Text_IO; use Ada.Text_IO;

procedure File_Exists is

  function Does_File_Exist (Name : String) return Boolean is
     The_File : Ada.Text_IO.File_Type;
  begin
     Open (The_File, In_File, Name);
     Close (The_File);
     return True;
  exception
     when Name_Error =>
        return False;
  end Does_File_Exist;

begin

  Put_Line (Boolean'Image (Does_File_Exist ("input.txt" )));
  Put_Line (Boolean'Image (Does_File_Exist ("\input.txt")));

end File_Exists;</lang> This example should work with any Ada 2005 compiler. <lang ada>with Ada.Text_IO; use Ada.Text_IO; with Ada.Directories; use Ada.Directories;

procedure File_Exists is

  procedure Print_File_Exist (Name : String) is
  begin
     Put_Line ("Does " & Name & " exist? " &
                 Boolean'Image (Exists (Name)));
  end Print_File_Exist;
  procedure Print_Dir_Exist (Name : String) is
  begin
     Put_Line ("Does directory " & Name & " exist? " &
                 Boolean'Image (Exists (Name) and then Kind (Name) = Directory));
  end Print_Dir_Exist;

begin

  Print_File_Exist ("input.txt" );
  Print_File_Exist ("/input.txt");
  Print_Dir_Exist ("docs");
  Print_Dir_Exist ("/docs");

end File_Exists;</lang>

Aikido

The stat function returns a System.Stat object for an existing file or directory, or null if it can't be found. <lang aikido> function exists (filename) {

   return stat (filename) != null

}

exists ("input.txt") exists ("/input.txt") exists ("docs") exists ("/docs")

</lang>

Applesoft BASIC

The error code for FILE NOT FOUND is 6. <lang ApplesoftBasic>100 F$ = "THAT FILE" 110 T$(0) = "DOES NOT EXIST." 120 T$(1) = "EXISTS." 130 GOSUB 200"FILE EXISTS? 140 PRINT F$; " "; T$(E) 150 END

200 REM FILE EXISTS? 210 REM TRY 220 ON ERR GOTO 300"CATCH 230 PRINT CHR$(4); "VERIFY "; F$ 240 POKE 216, 0 : REM ONERR OFF 250 E = 1 260 GOTO 350"END TRY 300 REM CATCH 310 E = PEEK(222) <> 6 320 POKE 216, 0 : REM ONERR OFF 330 IF E THEN RESUME : REM THROW 340 CALL - 3288 : REM RECOVER 350 REM END TRY 360 RETURN </lang>

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.

Another option is AutoHotkey's IfExist/IfNotExist command

<lang autohotkey>; FileExist() function examples ShowFileExist("input.txt") ShowFileExist("\input.txt") ShowFolderExist("docs") ShowFolderExist("\docs")

IfExist/IfNotExist command examples (from documentation)

IfExist, D:\

 MsgBox, The drive exists.

IfExist, D:\Docs\*.txt

 MsgBox, At least one .txt file exists.

IfNotExist, C:\Temp\FlagFile.txt

 MsgBox, The target file does not exist.

Return

ShowFileExist(file) {

 If (FileExist(file) && !InStr(FileExist(file), "D"))
   MsgBox, file: %file% exists.
 Else
   MsgBox, file: %file% does NOT exist.
 Return

}

ShowFolderExist(folder) {

 If InStr(FileExist(folder), "D")
   MsgBox, folder: %folder% exists.
 Else
   MsgBox, folder: %folder% does NOT exist.
 Return

}</lang>

AWK

Works with: gawk

<lang awk>@load "filefuncs" BEGIN {

   exists("input.txt")
   exists("/input.txt")
   exists("docs")
   exists("/docs")

}

function exists(name ,fd) {

   if ( stat(name, fd) == -1)
     print name " doesn't exist"
   else
     print name " exists"

}</lang>

Getline method. Also works in a Windows environment. <lang AWK>BEGIN {

   exists("input.txt")
   exists("\\input.txt")
   exists("docs")
   exists("\\docs")
   exit(0)

}

  1. Check if file or directory exists, even 0-length file.
  2. Return 0 if not exist, 1 if exist

function exists(file ,line, msg) {

       if ( (getline line < file) == -1 )
       {
               # "Permission denied" is for MS-Windows
               msg = (ERRNO ~ /Permission denied/ || ERRNO ~ /a directory/) ? "1" : "0"
               close(file)
               return msg
       }
       else {
               close(file)
               return 1
       }

}</lang>

Works with: gawk

Check file only (no directories) <lang>gawk 'BEGINFILE{if (ERRNO) {print "Not exist."; exit} } {print "Exist."; exit}' input.txt</lang>

Axe

<lang axe>If GetCalc("appvINPUT")

Disp "EXISTS",i

Else

Disp "DOES NOT EXIST",i

End</lang>

BASIC

Works with: QBasic

<lang qbasic> ON ERROR GOTO ohNo f$ = "input.txt" GOSUB opener f$ = "\input.txt" GOSUB opener

'can't directly check for directories, 'but can check for the NUL device in the desired dir f$ = "docs\nul" GOSUB opener f$ = "\docs\nul" GOSUB opener END

opener:

   e$ = " found"
   OPEN f$ FOR INPUT AS 1
   PRINT f$; e$
   CLOSE
   RETURN

ohNo:

   IF (53 = ERR) OR (76 = ERR) THEN
       e$ = " not" + e$
   ELSE
       e$ = "Unknown error"
   END IF
   RESUME NEXT

</lang>

You can also check for a directory by trying to enter it.

<lang qbasic> ON ERROR GOTO ohNo d$ = "docs" CHDIR d$ d$ = "\docs" CHDIR d$ END

ohNo:

   IF 76 = ERR THEN
       PRINT d$; " not found"
   ELSE
       PRINT "Unknown error"
   END IF
   RESUME NEXT

</lang>

Works with: QuickBasic version 7.1
Works with: PowerBASIC for DOS

Later versions of MS-compatible BASICs include the DIR$ keyword, which makes this pretty trivial.

<lang qbasic> f$ = "input.txt" GOSUB opener f$ = "\input.txt" GOSUB opener

'can't directly check for directories, 'but can check for the NUL device in the desired dir f$ = "docs\nul" GOSUB opener f$ = "\docs\nul" GOSUB opener END

opener:

   d$ = DIR$(f$)
   IF LEN(d$) THEN
       PRINT f$; " found"
   ELSE
       PRINT f$; " not found"
   END IF
   RETURN

</lang>

Batch File

<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.</lang>

BBC BASIC

<lang bbcbasic> test% = OPENIN("input.txt")

     IF test% THEN
       CLOSE #test%
       PRINT "File input.txt exists"
     ENDIF
     
     test% = OPENIN("\input.txt")
     IF test% THEN
       CLOSE #test%
       PRINT "File \input.txt exists"
     ENDIF
     
     test% = OPENIN("docs\NUL")
     IF test% THEN
       CLOSE #test%
       PRINT "Directory docs exists"
     ENDIF
     
     test% = OPENIN("\docs\NUL")
     IF test% THEN
       CLOSE #test%
       PRINT "Directory \docs exists"
     ENDIF</lang>

C

Library: POSIX

<lang c>#include <sys/types.h>

  1. include <sys/stat.h>
  2. include <stdio.h>
  3. include <unistd.h>

/* Check for regular file. */ int check_reg(const char *path) { struct stat sb; return stat(path, &sb) == 0 && S_ISREG(sb.st_mode); }

/* Check for directory. */ int check_dir(const char *path) { struct stat sb; return stat(path, &sb) == 0 && S_ISDIR(sb.st_mode); }

int main() { printf("input.txt is a regular file? %s\n", check_reg("input.txt") ? "yes" : "no"); printf("docs is a directory? %s\n", check_dir("docs") ? "yes" : "no"); printf("/input.txt is a regular file? %s\n", check_reg("/input.txt") ? "yes" : "no"); printf("/docs is a directory? %s\n", check_dir("/docs") ? "yes" : "no"); return 0; }</lang>

C++

Library: boost

<lang cpp>#include "boost/filesystem.hpp"

  1. include <string>
  2. include <iostream>

void testfile(std::string name) {

 boost::filesystem::path file(name);
 if (exists(file))
 {
   if (is_directory(file))
     std::cout << name << " is a directory.\n";
   else
     std::cout << name << " is a non-directory file.\n";
 }
 else
   std::cout << name << " does not exist.\n";

}

int main() {

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

}</lang>

C#

<lang csharp>using System.IO;

Console.WriteLine(File.Exists("input.txt")); Console.WriteLine(File.Exists("/input.txt")); Console.WriteLine(Directory.Exists("docs")); Console.WriteLine(Directory.Exists("/docs"));</lang>

CoffeeScript

Works with: Node.js

<lang coffeescript> fs = require 'fs' path = require 'path'

root = path.resolve '/' current_dir = __dirname filename = 'input.txt' dirname = 'docs'

local_file = path.join current_dir, filename local_dir = path.join current_dir, dirname

root_file = path.join root, filename root_dir = path.join root, dirname

for p in [ local_file, local_dir, root_file, root_dir ] then do ( p ) ->

   fs.exists p, ( p_exists ) ->
       unless p_exists
           console.log "#{ p } does not exist."
       else then fs.stat p, ( error, stat ) ->
           console.log "#{ p } exists and is a #{ if stat.isFile() then 'file' else then 'directory' }."
           

</lang>

Clojure

<lang clojure>

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

</lang>

Common Lisp

probe-file returns nil if a file does not exist. directory returns nil if there are no files in a specified directory. <lang lisp>(if (probe-file (make-pathname :name "input.txt"))

   (print "rel file exists"))

(if (probe-file (make-pathname :directory '(:absolute "") :name "input.txt"))

   (print "abs file exists"))

(if (directory (make-pathname :directory '(:relative "docs")))

   (print "rel directory exists")
   (print "rel directory is not known to exist"))

(if (directory (make-pathname :directory '(:absolute "docs")))

   (print "abs directory exists")
   (print "abs directory is not known to exist"))</lang>

There is no standardized way to determine if an empty directory exists, as Common Lisp dates from before the notion of directories as a type of file was near-universal. CL-FAD provides many of the therefore-missing capabilities in a cross-implementation library.

Library: CL-FAD

<lang lisp>(if (cl-fad:directory-exists-p (make-pathname :directory '(:relative "docs")))

   (print "rel directory exists")
   (print "rel directory does not exist"))</lang>

D

<lang d>import std.stdio, std.file, std.path;

void verify(in string name) {

   if (name.exists())
       writeln("'", name, "' exists");
   else
       writeln("'", name, "' doesn't exist");

}

void main() {

   // check in current working dir
   verify("input.txt");
   verify("docs");
   // check in root
   verify(dirSeparator ~ "input.txt");
   verify(dirSeparator ~ "docs");

}</lang>

Output:
'input.txt' doesn't exist
'docs' doesn't exist
'\input.txt' doesn't exist
'\docs' doesn't exist

DCL

<lang DCL>$ if f$search( "input.txt" ) .eqs. "" $ then $ write sys$output "input.txt not found" $ else $ write sys$output "input.txt found" $ endif $ if f$search( "docs.dir" ) .eqs. "" $ then $ write sys$output "directory docs not found" $ else $ write sys$output "directory docs found" $ endif $ if f$search( "[000000]input.txt" ) .eqs. "" $ then $ write sys$output "[000000]input.txt not found" $ else $ write sys$output "[000000]input.txt found" $ endif $ if f$search( "[000000]docs.dir" ) .eqs. "" $ then $ write sys$output "directory [000000]docs not found" $ else $ write sys$output "directory [000000]docs found" $ endif</lang>

Output:
$ @check_that_file_exists
input.txt found
directory docs not found
[000000]input.txt not found
directory [000000]docs not found

Delphi

<lang Delphi>program EnsureFileExists;

{$APPTYPE CONSOLE}

uses

 SysUtils;

begin

 if FileExists('input.txt') then
   Writeln('File "input.txt" exists.')
 else
   Writeln('File "input.txt" does not exist.');
 if FileExists('\input.txt') then
   Writeln('File "\input.txt" exists.')
 else
   Writeln('File "\input.txt" does not exist.');
 if DirectoryExists('docs') then
   Writeln('Directory "docs" exists.')
 else
   Writeln('Directory "docs" does not exists.');
 if DirectoryExists('\docs') then
   Writeln('Directory "\docs" exists.')
 else
   Writeln('Directory "\docs" does not exists.');

end.</lang>

E

<lang e>for file in [<file:input.txt>,

            <file:///input.txt>] {
 require(file.exists(),       fn { `$file is missing!` })
 require(!file.isDirectory(), fn { `$file is a directory!` })

}

for file in [<file:docs>,

            <file:///docs>] {
 require(file.exists(),      fn { `$file is missing!` })
 require(file.isDirectory(), fn { `$file is not a directory!` })

}</lang>

Elixir

<lang Elixir> File.exists?("file.txt") File.exists?("fi1e.txt") </lang>

<lang Elixir> File.exists?("/fi1e.txt") File.exists?("/fi1e.txt") </lang>

Output:

true
false

true
false

Emacs Lisp

<lang Lisp>(file-exists-p "input.txt") (file-directory-p "docs") (file-exists-p "/input.txt") (file-directory-p "/docs")</lang>

file-exists-p is true on both files and directories. file-directory-p is true only on directories. Both go through the file-name-handler-alist "magic filenames" mechanism so can act on remote files. On MS-DOS generally both / and \ work to specify the root directory.

Erlang

<lang erlang>#!/usr/bin/escript existence( true ) ->"exists"; existence( false ) ->"does not exist".

print_result(Type, Name, Flag) -> io:fwrite( "~s ~s ~s~n", [Type, Name, existence(Flag)] ).


main(_) ->

       print_result( "File", "input.txt", filelib:is_regular("input.txt") ),
       print_result( "Directory", "docs", filelib:is_dir("docs") ),
       print_result( "File", "/input.txt", filelib:is_regular("/input.txt") ),
       print_result( "Directory", "/docs", filelib:is_dir("/docs") ).

</lang>

Euphoria

<lang euphoria>include file.e

procedure ensure_exists(sequence name)

   object x
   sequence s
   x = dir(name)
   if sequence(x) then
       if find('d',x[1][D_ATTRIBUTES]) then
           s = "directory"
       else
           s = "file"
       end if
       printf(1,"%s %s exists.\n",{name,s})
   else
       printf(1,"%s does not exist.\n",{name})
   end if

end procedure

ensure_exists("input.txt") ensure_exists("docs") ensure_exists("/input.txt") ensure_exists("/docs")</lang>

F#

<lang fsharp>open System.IO File.Exists("input.txt") Directory.Exists("docs") File.Exists("/input.txt") Directory.Exists(@"\docs")</lang>

Factor

<lang factor>: print-exists? ( path -- )

   [ write ": " write ] [ exists? "exists." "doesn't exist." ? print ] bi ;

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

Forth

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

s" input.txt" .exists

s" /input.txt" .exists

s" docs" .exists

s" /docs" .exists</lang>

Fortran

Works with: Fortran version 90 and later

Cannot check for directories in Fortran <lang fortran>LOGICAL :: file_exists INQUIRE(FILE="input.txt", EXIST=file_exists)  ! file_exists will be TRUE if the file

                                              ! exists and FALSE otherwise

INQUIRE(FILE="/input.txt", EXIST=file_exists)</lang>

Actually, f90,f95 are able to deal with directory staff:

<lang fortran>logical :: dir_e ! a trick to be sure docs is a dir inquire( file="./docs/.", exist=dir_e ) if ( dir_e ) then

 write(*,*), "dir exists!"

else

 ! workaround: it calls an extern program...
 call system('mkdir docs')

end if</lang>

GAP

<lang gap>IsExistingFile("input.txt"); IsDirectoryPath("docs"); IsExistingFile("/input.txt"); IsDirectoryPath("/docs");</lang>

Go

<lang go>package main

import (

   "fmt"
   "os"

)

func printStat(p string) {

   switch i, err := os.Stat(p); {
   case err != nil:
       fmt.Println(err)
   case i.IsDir():
       fmt.Println(p, "is a directory")
   default:
       fmt.Println(p, "is a file")
   }

}

func main() {

   printStat("input.txt")
   printStat("/input.txt")
   printStat("docs")
   printStat("/docs")

}</lang>

Groovy

<lang groovy>println new File('input.txt').exists() println new File('/input.txt').exists() println new File('docs').exists() println new File('/docs').exists()</lang>

Haskell

<lang haskell>import System.IO import System.Directory

check :: (FilePath -> IO Bool) -> FilePath -> IO () check p s = do

 result <- p s
 putStrLn $ s ++ if result then " does exist" else " does not exist"

main = do

 check doesFileExist "input.txt"
 check doesDirectoryExist "docs"
 check doesFileExist "/input.txt"
 check doesDirectoryExist "/docs"</lang>

HicEst

<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 </lang>

Icon and Unicon

Icon doesn't support 'stat'; however, information can be obtained by use of the system function to access command line. <lang 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.") 
  }</lang>

Note: Icon and Unicon accept both / and \ for directory separators.

IDL

<lang idl> print, FILE_TEST('input.txt') print, FILE_TEST(PATH_SEP()+'input.txt') print, FILE_TEST('docs', /DIRECTORY) print, FILE_TEST(PATH_SEP()+'docs', /DIRECTORY)

</lang>

J

<lang j>require 'files' fexist 'input.txt' fexist '/input.txt' direxist=: 2 = ftype direxist 'docs' direxist '/docs'</lang>

Java

<lang java>import java.io.File; public class FileExistsTest {

  public static boolean isFileExists(String filename) {
      boolean exists = new File(filename).exists();
      return exists;
  }
  public static void test(String type, String filename) {
      System.out.println("The following " + type + " called " + filename + 
          (isFileExists(filename) ? " exists." : " not exists.")
      );
  }
  public static void main(String args[]) {
       test("file", "input.txt");
       test("file", File.separator + "input.txt");
       test("directory", "docs");
       test("directory", File.separator + "docs" + File.separator);
  }

}</lang>

Works with: Java version 7+

<lang java5>import java.nio.file.FileSystem; import java.nio.file.FileSystems; import java.nio.file.Files; public class FileExistsTest{

  private static FileSystem defaultFS = FileSystems.getDefault();
  public static boolean isFileExists(String filename){
      return Files.exists(defaultFS.getPath(filename));
  }
  public static void test(String type, String filename){
      System.out.println("The following " + type + " called " + filename + 
          (isFileExists(filename) ? " exists." : " not exists.")
      );
  }
  public static void main(String args[]){
       test("file", "input.txt");
       test("file", defaultFS.getSeparator() + "input.txt");
       test("directory", "docs");
       test("directory", defaultFS.getSeparator() + "docs" + defaultFS.getSeparator());
  }

}</lang>

JavaScript

Works with: JScript

<lang javascript>var fso = new ActiveXObject("Scripting.FileSystemObject");

fso.FileExists('input.txt'); fso.FileExists('c:/input.txt'); fso.FolderExists('docs'); fso.FolderExists('c:/docs');</lang>

Julia

<lang julia>isfile("input.txt") isfile("/input.txt") isdir("docs") isdir("/docs")</lang>

LabVIEW

Library: LabVIEW CWD

This image is a VI Snippet, an executable image of LabVIEW code. The LabVIEW version is shown on the top-right hand corner. You can download it, then drag-and-drop it onto the LabVIEW block diagram from a file browser, and it will appear as runnable, editable code.
 


Lasso

<lang Lasso>// local file file_exists('input.txt')

// local directory file_exists('docs')

// file in root file system (requires permissions at user OS level) file_exists('//input.txt')

// directory in root file system (requires permissions at user OS level) file_exists('//docs')</lang>

LFE

From the LFE REPL: <lang lisp> > (: filelib is_regular '"input.txt") false > (: filelib is_dir '"docs") false > (: filelib is_regular '"/input.txt") false > (: filelib is_dir '"/docs")) false </lang>

Liberty BASIC

<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$ if fileExists(fpath$) then

   print fpath$; " exists!"

else

   print fpath$; " doesn't exist!"

end if end

'return a true if the file in fullPath$ exists, else return false function fileExists(fullPath$)

   files pathOnly$(fullPath$), filenameOnly$(fullPath$), info$()
   fileExists = val(info$(0, 0)) > 0

end function

'return just the directory path from a full file path function pathOnly$(fullPath$)

   pathOnly$ = fullPath$
   while right$(pathOnly$, 1) <> "\" and pathOnly$ <> ""
       pathOnly$ = left$(pathOnly$, len(pathOnly$)-1)
   wend

end function

'return just the filename from a full file path function filenameOnly$(fullPath$)

   pathLength = len(pathOnly$(fullPath$))
   filenameOnly$ = right$(fullPath$, len(fullPath$)-pathLength)

end function</lang>

Works with: UCB Logo

<lang logo>show file? "input.txt show file? "/input.txt show file? "docs show file? "/docs</lang> Alternatively, one can set a file prefix used for subsequent file commands. <lang logo>setprefix "/ show file? "input.txt</lang>

Lua

For directories, the following only works on platforms on which directories can be opened for reading like files. <lang lua>function output( s, b )

   if b then
       print ( s, " does not exist." )
   else
       print ( s, " does exist." )
   end    

end

output( "input.txt", io.open( "input.txt", "r" ) == nil ) output( "/input.txt", io.open( "/input.txt", "r" ) == nil ) output( "docs", io.open( "docs", "r" ) == nil ) output( "/docs", io.open( "/docs", "r" ) == nil )</lang>

The following more portable solution uses LuaFileSystem. <lang lua>require "lfs" for i, path in ipairs({"input.txt", "/input.txt", "docs", "/docs"}) do

   local mode = lfs.attributes(path, "mode")
   if mode then
       print(path .. " exists and is a " .. mode .. ".")
   else
       print(path .. " does not exist.")
   end

end</lang>


Maple

<lang Maple>with(FileTools): Exists("input.txt"); Exists("docs") and IsDirectory("docs"); Exists("/input.txt"); Exists("/docs") and IsDirectory("/docs");</lang>

Mathematica

<lang Mathematica>wd = NotebookDirectory[]; FileExistsQ[wd <> "input.txt"] DirectoryQ[wd <> "docs"]

FileExistsQ["/" <> "input.txt"] DirectoryQ["/" <> "docs"]</lang>


MATLAB / Octave

<lang Matlab> exist('input.txt','file')

exist('/input.txt','file') 
exist('docs','dir') 
exist('/docs','dir')</lang>

MAXScript

<lang maxscript>-- Here doesFileExist "input.txt" (getDirectories "docs").count == 1 -- Root doesFileExist "\input.txt" (getDirectories "C:\docs").count == 1</lang>

Modula-3

<lang modula3>MODULE FileTest EXPORTS Main;

IMPORT IO, Fmt, FS, File, OSError, Pathname;

PROCEDURE FileExists(file: Pathname.T): BOOLEAN =

 VAR status: File.Status;
 BEGIN
   TRY
     status := FS.Status(file);
     RETURN TRUE;
   EXCEPT
   | OSError.E => RETURN FALSE;
   END;
 END FileExists;

BEGIN

 IO.Put(Fmt.Bool(FileExists("input.txt")) & "\n");
 IO.Put(Fmt.Bool(FileExists("/input.txt")) & "\n");
 IO.Put(Fmt.Bool(FileExists("docs/")) & "\n");
 IO.Put(Fmt.Bool(FileExists("/docs")) & "\n");

END FileTest.</lang>

Nemerle

Translation of: C#

<lang Nemerle>using System.Console; using System.IO;

WriteLine(File.Exists("input.txt")); WriteLine(File.Exists("/input.txt")); WriteLine(Directory.Exists("docs")); WriteLine(Directory.Exists("/docs"));</lang>

NetRexx

<lang NetRexx>/* NetRexx */ options replace format comments java crossref symbols binary

runSample(arg) return

-- . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . method isExistingFile(fn) public static returns boolean

 ff = File(fn)
 fExists = ff.exists() & ff.isFile()
 return fExists

-- . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . method isExistingDirectory(fn) public static returns boolean

 ff = File(fn)
 fExists = ff.exists() & ff.isDirectory()
 return fExists

-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ method runSample(arg) private static

 parse arg files
 if files =  then files = 'input.txt F docs D /input.txt F /docs D'
 loop while files.length > 0
   parse files fn ft files
   select case(ft.upper())
     when 'F' then do
       if isExistingFile(fn) then ex = 'exists'
       else                       ex = 'does not exist'
       say 'File fn' ex
       end
     when 'D' then do
       if isExistingDirectory(fn) then ex = 'exists'
       else                            ex = 'does not exist'
       say 'Directory fn' ex
       end
     otherwise do
       if isExistingFile(fn) then ex = 'exists'
       else                       ex = 'does not exist'
       say 'File fn' ex
       end
     end
   end
 return

</lang>

NewLISP

<lang NewLISP>(dolist (file '("input.txt" "/input.txt"))

 (if (file? file true)
     (println "file " file " exists")))

(dolist (dir '("docs" "/docs"))

 (if (directory? dir)
     (println "directory " dir " exists")))</lang>

Nim

<lang nim>import os

echo existsFile "input.txt" echo existsFile "/input.txt" echo existsDir "docs" echo existsDir "/docs"</lang>

Objective-C

<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");</lang>

Objeck

<lang objeck> use IO;

bundle Default {

 class Test {
   function : Main(args : String[]) ~ Nil {
     File->Exists("input.txt")->PrintLine();
     File->Exists("/input.txt")->PrintLine();
     Directory->Exists("docs")->PrintLine();
     Directory->Exists("/docs")->PrintLine();
   }

} </lang>

OCaml

<lang ocaml>Sys.file_exists "input.txt";; Sys.file_exists "docs";; Sys.file_exists "/input.txt";; Sys.file_exists "/docs";;</lang>

ooRexx

<lang oorexx>/**********************************************************************

  • exists(filespec)
  • returns 1 if filespec identifies a file with size>0
  • (a file of size 0 is deemed not to exist.)
  • or a directory
  • 0 otherwise
  • 09.06.2013 Walter Pachl (retrieved from my toolset)
                                                                                                                                            • /

exists:

 parse arg spec
 call sysfiletree spec, 'LIST', 'BL'
 if list.0\=1 then return 0        -- does not exist
 parse var list.1 . . size flags .
 if size>0 then return 1           -- real file
 If substr(flags,2,1)='D' Then Do
   Say spec 'is a directory'
   Return 1
   End
 If size=0 Then Say spec 'is a zero-size file'
 Return 0</lang>

Oz

<lang oz>declare

 [Path] = {Module.link ['x-oz://system/os/Path.ozf']}

in

 {Show {Path.exists "docs"}}
 {Show {Path.exists "input.txt"}}
 {Show {Path.exists "/docs"}}
 {Show {Path.exists "/input.txt"}}</lang>

PARI/GP

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

A better version would use externstr.

Under PARI it would typically be more convenient to use C methods.

Pascal

See Delphi

Phix

<lang Phix>constant fd = {"file","directory"}

procedure check(string name) object d = dir(name)

   if sequence(d) then
       d = (find('d',d[1][D_ATTRIBUTES])!=0)
       printf(1,"%s %s exists.\n",{fd[1+d],name})
   else
       printf(1,"%s does not exist.\n",{name})
   end if

end procedure

check("input.txt") check("docs") check("/input.txt") check("/docs") check("/pagefile.sys") check("/Program Files (x86)")</lang>

Output:
input.txt does not exist.
directory docs exists.
/input.txt does not exist.
/docs does not exist.
file /pagefile.sys exists.
directory /Program Files (x86) exists.

PHP

<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';</lang>

Perl

<lang perl>use File::Spec::Functions qw(catfile rootdir);

  1. here

print -e 'input.txt'; print -d 'docs';

  1. root dir

print -e catfile rootdir, 'input.txt'; print -d catfile rootdir, 'docs';</lang>

Without a Perl Module

A 1 is printed if the file or dir exists.

perl -e 'print -e "./input.txt", "\n";'
perl -e 'print -d "./docs", "\n";'
perl -e 'print -e "/input.txt", "\n";'
perl -e 'print -d "/docs", "\n";'

Perl 6

<lang perl6>'input.txt'.IO ~~ :e; 'docs'.IO ~~ :d; '/input.txt'.IO ~~ :e; '/docs'.IO ~~ :d</lang>

PicoLisp

<lang PicoLisp>(if (info "file.txt")

  (prinl "Size: " (car @) " bytes, last modified " (stamp (cadr @) (cddr @)))
  (prinl "File doesn't exist") )</lang>

Pike

<lang pike>import Stdio;

int main(){

  if(exist("/var")){
     write("/var exists!\n");
  }
  if(exist("file-exists.pike")){
     write("I exist!\n");
  }

}</lang>

PL/I

<lang pli>*Process source or(!);

/*********************************************************************
* 20.10.2013 Walter Pachl
* 'set dd:f=d:\_l\xxx.txt,recsize(300)'
* 'tex'
*********************************************************************/
tex: Proc Options(main);
Dcl fid Char(30) Var Init('D:\_l\tst.txt');
Dcl xxx Char(30) Var Init('D:\_l\nix.txt');
Dcl r   Char(1000) Var;
Dcl f Record input;
On Undefinedfile(f) Goto label;
Open File(f) Title('/'!!fid);
Read file(f) Into(r);
Put Skip List('First line of file '!!fid!!': '!!r);
Close File(f);
Open File(f) Title('/'!!xxx);
Read file(f) Into(r);
Put Skip List(r);
Close File(f);
Label: Put Skip List('File '!!xxx!!' not found');
End;</lang>
Output:
  
First line of file D:\_l\tst.txt: Test line 1
File D:\_l\nix.txt not found    

Pop11

<lang pop11>sys_file_exists('input.txt') => sys_file_exists('/input.txt') => sys_file_exists('docs') => sys_file_exists('/docs') =></lang>

Note that the above literally checks for existence. Namely sys_file_exists returns true if file exists but can not be read.

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:

<lang pop11>;;; Define an auxilary function, returns boolean define file_readable(fname);

  lvars f = sysopen(fname, 0, true, `A`);
  if f then
      sysclose(f);
      return (true);
  else
      return (false);
  endif;

enddefine;</lang>

The above works but is not the only way or the best way to check status of a file in Pop11. There is a very general procedure sys_file_stat that allows interrogation of a file or directory. The full documentation can be seen in the online documentation (search for sys_file_stat):

http://wwwcgi.rdg.ac.uk:8081/cgi-bin/cgiwrap/wsi14/poplog/pop11/ref/sysio

http://www.poplog.org/docs/popdocs/pop11/ref/sysio

http://www.cs.bham.ac.uk/research/projects/poplog/doc/popref/sysio (Not so well formatted).

Users can easily define special cases of the general procedure.

PowerShell

<lang powershell> Test-Path input.txt</lang>


Prolog

Works with: SWI-Prolog version 6.6

<lang prolog>

exists_file('input.txt'), exists_directory('docs').

exits_file('/input.txt'), exists_directory('/docs').

</lang>

PureBasic

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

EndIf

result = ReadFile(#PB_Any, "/input.txt") If result>0 : Debug "this root file exists"

 Else : Debug "result=" +Str(result) +" so this root file is missing"

EndIf

result = ExamineDirectory(#PB_Any,"docs","") If result>0 : Debug "this local directory exists"

 Else : Debug "result=" +Str(result) +" so this local directory is missing"

EndIf

result = ExamineDirectory(#PB_Any,"/docs","") If result>0 : Debug "this root directory exists"

 Else : Debug "result=" +Str(result) +" so this root directory is missing"

EndIf </lang>

Python

Works with: Python version 2.5

The os.path.exists method will return True if a path exists False if it does not.

<lang python>import os

os.path.exists("input.txt") os.path.exists("/input.txt") os.path.exists("docs") os.path.exists("/docs")</lang>

R

<lang R>file.exists("input.txt") file.exists("/input.txt") file.exists("docs") file.exists("/docs")

  1. or

file.exists("input.txt", "/input.txt", "docs", "/docs")</lang>

The function file.exists returns a logical value (or a vector of logical values if more than one argument is passed)

Racket

<lang Racket>

  1. lang racket
here

(file-exists? "input.txt") (file-exists? "docs")

in the root

(file-exists? "/input.txt") (file-exists? "/docs")

or in the root with relative paths

(parameterize ([current-directory "/"])

 (and (file-exists? "input.txt")
      (file-exists? "docs")))

</lang>

Raven

<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</lang>

REBOL

<lang REBOL>exists? %input.txt exists? %docs/

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

REXX

version 1

Works with: PC/REXX
Works with: Personal REXX
Works with: Regina

<lang rexx>/*REXX pgm creates a new empty file and directory; in curr dir and root.*/ fn='input.txt' dn='docs' @.1='current directory'; @.2='root directory' /*msgs for each pass.*/ parse upper version v; regina=pos('REGINA',v)\==0 /*Regina being used? */

 do j=1 for 2;    say                 /*perform these statements twice.*/
 if stream(fn,'C',"QUERY EXISTS")==  then say 'file ' fn " doesn't exist in the" @.j
                                       else say 'file ' fn    " does exist in the" @.j
 if dosisdir(dn)  then say 'directory ' dn    " does exist in the" @.j
                  else say 'directory ' dn " doesn't exist in the" @.j
 if regina  then call    chdir '\'    /*use Regina's version of  CHDIR.*/
            else call doschdir '\'    /*PC/REXX & Personal REXX version*/
 end   /*j*/                          /*now, go and perform them again.*/
                                      /*stick a fork in it, we're done.*/</lang>

version 2

Works with: ARexx

<lang rexx> /* Check if a file already exists */ filename='file.txt' IF ~Openfile(filename) THEN CALL Openfile(':'filename) EXIT 0 Openfile: IF ~Exists(filename) THEN RETURN 0 CALL Open(filehandle,filename,'APPEND') RETURN 1 </lang>

RLaB

RLaB provides two user functions for the task, isfile and isdir. <lang RLaB> >> isdir("docs")

 0

>> isfile("input.txt")

 0

</lang>

Ruby

File.exists? only checks if a file exists; it can be a regular file, a directory, or something else. File.file? or File.directory? checks for a regular file or a directory. Ruby also allows FileTest.file? or FileTest.directory?.

<lang ruby>File.file?("input.txt") File.file?("/input.txt") File.directory?("docs") File.directory?("/docs")</lang>

The next program runs all four checks and prints the results.

<lang ruby>["input.txt", "/input.txt"].each { |f|

 printf "%s is a regular file? %s\n", f, File.file?(f) }

["docs", "/docs"].each { |d|

 printf "%s is a directory? %s\n", d, File.directory?(d) }</lang>


Run BASIC

<lang runbasic>files #f,"input.txt" if #f hasanswer() = 1 then print "File does not exist"

files #f,"docs" if #f hasanswer() = 1 then print "File does not exist" if #f isDir() = 0 then print "This is a directory" </lang>

Scala

Library: Scala

<lang scala>import java.nio.file.{ Files, FileSystems }

object FileExistsTest extends App {

 val defaultFS = FileSystems.getDefault()
 val separator = defaultFS.getSeparator()
 def test(filename: String) {
   val path = defaultFS.getPath(filename)
   println(s"The following ${if (Files.isDirectory(path)) "directory" else "file"} called $filename" +
     (if (Files.exists(path)) " exists." else " not exists."))
 }
 // main
 List("output.txt", separator + "output.txt", "docs", separator + "docs" + separator).foreach(test)

}</lang>

Scheme

Works with: Scheme version R6RS

[1]

<lang scheme>(file-exists? filename)</lang>

Seed7

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

const proc: main is func

 begin
   writeln(fileType("input.txt") = FILE_REGULAR);
   writeln(fileType("/input.txt") = FILE_REGULAR);
   writeln(fileType("docs") = FILE_DIR);
   writeln(fileType("/docs") = FILE_DIR);
 end func;</lang>

Sidef

<lang ruby># Here say (Dir.cwd + %f'input.txt' -> is_file); say (Dir.cwd + %d'docs' -> is_dir);

  1. Root

say (Dir.root + %f'input.txt' -> is_file); say (Dir.root + %d'docs' -> is_dir);</lang> NOTE: To check only for existence, use the method exists

Slate

<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</lang>

Smalltalk

Squeak has no notion of 'current directory' because it isn't tied to the shell that created it.

<lang smalltalk>FileDirectory new fileExists: 'c:\serial'. (FileDirectory on: 'c:\') directoryExists: 'docs'.</lang>

In GNU Smalltalk instead you can do:

<lang smalltalk>(Directory name: 'docs') exists ifTrue: [ ... ] (Directory name: 'c:\docs') exists ifTrue: [ ... ] (File name: 'serial') isFile ifTrue: [ ... ] (File name: 'c:\serial') isFile ifTrue: [ ... ]</lang>

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

Standard ML

<lang sml>OS.FileSys.access ("input.txt", []); OS.FileSys.access ("docs", []); OS.FileSys.access ("/input.txt", []); OS.FileSys.access ("/docs", []);</lang>

Tcl

Taking the meaning of the task from the DOS example: <lang tcl>if { [file exists "input.txt"] } {

   puts "input.txt exists"

}

if { [file exists [file nativename "/input.txt"]] } {

   puts "/input.txt exists"

}

if { [file isdirectory "docs"] } {

   puts "docs exists and is a directory"

}

if { [file isdirectory [file nativename "/docs"]] } {

   puts "/docs exists and is a directory"

}</lang> Note that these operations do not require the use of file nativename on either Windows or any version of Unix.

Toka

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

TUSCRIPT

<lang tuscript> $$ MODE TUSCRIPT file="input.txt",directory="docs" IF (file=='file') THEN PRINT file, " exists" ELSE PRINT/ERROR file," not exists" ENDIF IF (directory=='project') THEN PRINT directory," exists" ELSE PRINT/ERROR "directory ",directory," not exists" ENDIF </lang>

Output:
input.txt exists
@@@@@@@@  directory docs not exists                                    @@@@@@@@ 

UNIX Shell

<lang bash>test -f input.txt test -f /input.txt test -d docs test -d /docs</lang>

The next program runs all four checks and prints the results.

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

Vedit macro language

Vedit allows using either '\' or '/' as directory separator character, it is automatically converted to the one used by the operating system. <lang vedit>// In current directory 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") }

// In the root 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") }</lang>

Visual Basic .NET

Platform: .NET

Works with: Visual Basic .NET version 9.0+

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

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

'Root, platform independent Console.WriteLine(If(IO.Directory.Exists(IO.Path.DirectorySeparatorChar & "docs"), _

  "directory exists", "directory doesn't exists"))

Console.WriteLine(If(IO.Directory.Exists(IO.Path.DirectorySeparatorChar & "output.txt"), _

 "file exists", "file doesn't exists"))</lang>

VBScript

<lang vbscript>Set FSO=CreateObject("Scripting.FileSystemObject") Function FileExists(strFile) if FSO.fileExists(strFile) then FileExists=true else FileExists=false end if end function

Function folderExists(strFolder) if FSO.folderExists(strFolder) then folderExists=true else folderexists=false end if end function

usage (apostrophes indicate comments-this section will not be run) 'if fileExists("C:\test.txt") then 'msgbox"It Exists!" 'else 'msgbox"awww" 'end if ''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''' </lang>

zkl

<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 </lang>