Checking file existence

From CodeCodex

Implementations[edit]

C[edit]

#include <stdbool.h>
#include <stdio.h>

bool exists(const char *filename)
{
   FILE *f = fopen(filename, "r");

   if (!f) return false;

   fclose(f);

   return true;
}

The (ISO C) solution cited above mistakes existence for readability and, at least on modern Unices, modifies the access time of the file in question. A better (POSIX) solution is something like this:

#include <unistd.h>

int exists(const char *filename) {
    return !access(filename, F_OK);
}

Or even shorter:

#include <unistd.h>

#define exists(filename) (!access(filename, F_OK))

Note that all three of these are blind to the type of file, so symbolic links and other special files -- including directories for the access() tests -- will return true.

C++[edit]

Checking for existence by opening the file (see note for C).

#include <fstream>
#include <string>
bool file_exists(const std::string& s) {
  std::ifstream iff(s.c_str());
  return iff.is_open();
}

C#[edit]

C# has a built-in static function to accomplish this:

 File.Exists(string filename); 

The filename can be absolute or relative to the current working directory. The base class library also provides an instance function:

 FileInfo myFile = new FileInfo(string fileName); 
 bool fileExists = myFile.Exists;

Common Lisp[edit]

(probe-file "/foo/bar")

Java[edit]

String path = "c:\\temp\\MyTest.txt";
if (new File(path).exists())
   System.out.println("file exists");

But since java is operating system agnostic a forward slash ('/') can be used

String path = "/temp/MyTest.txt";
if (new File(path).exists())
   System.out.println("file exists");

Or you can use the File.separator property which is the correct slash for the run time environment.

String path = "folder"+File.separator+"file.txt";
if (new File(path).exists())
   System.out.println("file exists");

Objective Caml[edit]

if Sys.file_exists "/foo/bar" then print_endline "File exists."

Perl[edit]

The builtin function -e returns true if a file exists.

print "File exists.\n" if -e '/foo/bar';

PHP[edit]

if(file_exists("/foo/bar"))
{echo "File exists!";}
Second Option (Function Style)
function fileExists($filename) {
if(file_exists($filename))
return 1; //or if you want it to say something then use echo
}

Python[edit]

Python has a function to accomplish this, os.path.isfile will determine if a file exists and is a regular file. Example:

import os

if os.path.isfile('/foo/bar'):
   print 'file exists!'

To test a simple existence of the object without specyfing if it is a file, a directory or anything else use os.path.exists :

import os

if os.path.exists('/foo/bar'):
   print 'object exists!'

Ruby[edit]

The class method File.exist?() can be used to test whether a file exists or not.
It returns true when the file exists, and false when it doesn't.

File.exist?(file_name)

Alternatively,

test ?e, file_name

To check if the file is a regular file:

FileTest.file?("/foo/bar")

Or work with error-handling:

begin
 puts File.ftype("/foo/bar")+" exists!" 
rescue Errno::ENOENT
 puts "File not found!"
end

Seed7[edit]

if fileType("/foo/bar") <> FILE_ABSENT then
  writeln("file exists!");
end if;

Shell[edit]

test -f /foo/bar && echo "File exist" 

Tcl[edit]

if {[file exists "/foo/bar"] == 1} {
   puts "file exists!";
}

Visual Basic[edit]

Dim objFileSystem as Object
'Dim objFileSystem as FileSystemObject if you have added
'the references Microsoft Scripting Runtime
Dim FileToCheck as String

Set objFileSystem = CreateObject("Scripting.FileSystemObject")
'Use objFileSystem = New FileSystemObject if references added

FileToCheck = "C:\temp\MyTest.txt"
If objFileSystem.FileExists(FileToCheck) Then
    Debug.Print "File " & FileToCheck & " exists!"
End If

Set objFileSystem = Nothing


See Determining Filesystem Object Information for determining information beyond simple existence.