Difference between revisions of "Checking file existence"

From CodeCodex

(Perl)
(c++ example added)
Line 36: Line 36:
  
 
Note that all three of these are blind to the type of file, so symbolic links and other special files -- including directories for the <tt>access()</tt> tests -- will return true.
 
Note that all three of these are blind to the type of file, so symbolic links and other special files -- including directories for the <tt>access()</tt> tests -- will return true.
 +
 +
===C++===
 +
 +
Checking for existence by opening the file (see note for C).
 +
<HIGHLIGHTSYNTAX language="c++">#include <fstream>
 +
bool file_exists(const string& s) {
 +
  ifstream iff(s.c_str());
 +
  return iff.is_open();
 +
}
 +
</HIGHLIGHTSYNTAX>
  
 
===C#===
 
===C#===
Line 172: Line 182:
  
 
[[Category:C]]
 
[[Category:C]]
 +
[[Category:C++]]
 
[[Category:C sharp]]
 
[[Category:C sharp]]
 
[[Category:Common Lisp]]
 
[[Category:Common Lisp]]

Revision as of 10:41, 26 November 2009

Implementations

C

#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++

Checking for existence by opening the file (see note for C). <HIGHLIGHTSYNTAX language="c++">#include <fstream> bool file_exists(const string& s) {

 ifstream iff(s.c_str());
 return iff.is_open();

} </HIGHLIGHTSYNTAX>

C#

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

(probe-file "/foo/bar")

Java

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

Objective Caml

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

Perl

The builtin function -e returns true if a file exists. <HIGHLIGHTSYNTAX language="perl"> print "File exists.\n" if -e '/foo/bar'; </HIGHLIGHTSYNTAX>

PHP

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

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

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

Tcl

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

Visual Basic

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

Shell

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


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