Difference between revisions of "Checking file existence"

From CodeCodex

 
(5 intermediate revisions by 5 users not shown)
Line 1: Line 1:
 
==Implementations==
 
==Implementations==
 
===C===
 
===C===
<pre>
+
<pre class="c">
 
#include <stdbool.h>
 
#include <stdbool.h>
 
#include <stdio.h>
 
#include <stdio.h>
Line 19: Line 19:
 
The (ISO C) solution cited above mistakes existence for readability and, at least on modern [[Wikipedia:Unix|Unices]], modifies the access time of the file in question. A better ([[Wikipedia:POSIX|POSIX]]) solution is something like this:
 
The (ISO C) solution cited above mistakes existence for readability and, at least on modern [[Wikipedia:Unix|Unices]], modifies the access time of the file in question. A better ([[Wikipedia:POSIX|POSIX]]) solution is something like this:
  
<pre>
+
<pre class="c">
 
#include <unistd.h>
 
#include <unistd.h>
  
Line 29: Line 29:
 
Or even shorter:
 
Or even shorter:
  
<pre>
+
<pre class="c">
 
#include <unistd.h>
 
#include <unistd.h>
  
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).
 +
<pre class="c++">#include <fstream>
 +
#include <string>
 +
bool file_exists(const std::string& s) {
 +
  std::ifstream iff(s.c_str());
 +
  return iff.is_open();
 +
}
 +
</pre>
  
 
===C#===
 
===C#===
 
C# has a built-in static function to accomplish this:  
 
C# has a built-in static function to accomplish this:  
 +
<pre class="c#">
 
  File.Exists(string filename);  
 
  File.Exists(string filename);  
 +
</pre>
  
 
The filename can be absolute or relative to the current working directory. The base class library also provides an instance function:  
 
The filename can be absolute or relative to the current working directory. The base class library also provides an instance function:  
  
 +
<pre class="c#">
 
  FileInfo myFile = new FileInfo(string fileName);  
 
  FileInfo myFile = new FileInfo(string fileName);  
 
  bool fileExists = myFile.Exists;
 
  bool fileExists = myFile.Exists;
 +
</pre>
  
 
===Common Lisp===
 
===Common Lisp===
Line 52: Line 67:
  
 
===Java===
 
===Java===
<pre>
+
<pre class="java">
 
String path = "c:\\temp\\MyTest.txt";
 
String path = "c:\\temp\\MyTest.txt";
 
if (new File(path).exists())
 
if (new File(path).exists())
 
   System.out.println("file exists");
 
   System.out.println("file exists");
 
</pre>
 
</pre>
 +
 
But since java is operating system agnostic a forward slash ('/') can be used
 
But since java is operating system agnostic a forward slash ('/') can be used
  
<pre>
+
<pre class="java">
 
String path = "/temp/MyTest.txt";
 
String path = "/temp/MyTest.txt";
 
if (new File(path).exists())
 
if (new File(path).exists())
 
   System.out.println("file exists");
 
   System.out.println("file exists");
 
</pre>
 
</pre>
 +
 +
Or you can use the File.separator property which is the correct slash for the run time environment.
 +
 +
<pre class="java">
 +
String path = "folder"+File.separator+"file.txt";
 +
if (new File(path).exists())
 +
  System.out.println("file exists");
 +
</pre>
  
 
===Objective Caml===
 
===Objective Caml===
Line 71: Line 95:
  
 
===Perl===
 
===Perl===
In Perl, the builtin function <code>-e</code> returns <code>1</code> if a file exists, and <code>undef</code> otherwise.
+
The builtin function [http://perldoc.perl.org/functions/-X.html -e] returns true if a file exists.
 
+
Example:
+
 
<pre>
 
<pre>
print "File exists.\n" if (-e "/foo/bar");
+
print "File exists.\n" if -e '/foo/bar';
 
</pre>
 
</pre>
  
 
===PHP===
 
===PHP===
<pre>
+
<pre class="php">
 
if(file_exists("/foo/bar"))
 
if(file_exists("/foo/bar"))
 
{echo "File exists!";}
 
{echo "File exists!";}
 
</pre>
 
</pre>
  
<pre>
+
<pre class="php">
 
Second Option (Function Style)
 
Second Option (Function Style)
 
function fileExists($filename) {
 
function fileExists($filename) {
Line 93: Line 115:
  
 
===Python===
 
===Python===
Python has a function to accomplish this.  <code>os.path.isfile</code> will determine if a file exists and is a regular file.  Example:
+
Python has a function to accomplish this, os.path.isfile will determine if a file exists and is a regular file.  Example:
<pre>
+
<pre class="python">
 
import os
 
import os
  
Line 101: Line 123:
 
</pre>
 
</pre>
  
To test a simple existence of the object without specyfing if it is a file, a directory or anything else use <code>os.path.exists</code> :
+
To test a simple existence of the object without specyfing if it is a file, a directory or anything else use os.path.exists :
<pre>
+
<pre class="python">
 
import os
 
import os
  
Line 113: Line 135:
 
It returns true when the file exists, and false when it doesn't.
 
It returns true when the file exists, and false when it doesn't.
  
<pre>
+
<pre class="ruby">
 
File.exist?(file_name)
 
File.exist?(file_name)
 
</pre>
 
</pre>
Line 119: Line 141:
 
Alternatively,
 
Alternatively,
  
<pre>
+
<pre class="ruby">
 
test ?e, file_name
 
test ?e, file_name
 
</pre>
 
</pre>
Line 125: Line 147:
 
To check if the file is a regular file:
 
To check if the file is a regular file:
  
<pre>
+
<pre class="ruby">
 
FileTest.file?("/foo/bar")
 
FileTest.file?("/foo/bar")
 
</pre>
 
</pre>
Line 131: Line 153:
 
Or work with error-handling:
 
Or work with error-handling:
  
<pre>
+
<pre class="ruby">
 
begin
 
begin
 
  puts File.ftype("/foo/bar")+" exists!"  
 
  puts File.ftype("/foo/bar")+" exists!"  
Line 137: Line 159:
 
  puts "File not found!"
 
  puts "File not found!"
 
end
 
end
 +
</pre>
 +
 +
===Seed7===
 +
<pre>
 +
if fileType("/foo/bar") <> FILE_ABSENT then
 +
  writeln("file exists!");
 +
end if;
 +
</pre>
 +
 +
===Shell===
 +
<pre>
 +
test -f /foo/bar && echo "File exist"
 
</pre>
 
</pre>
  
 
===Tcl===
 
===Tcl===
 
<pre>
 
<pre>
if {[file exists "/foo/bar"] == 1}
+
if {[file exists "/foo/bar"] == 1} {
{
+
 
   puts "file exists!";
 
   puts "file exists!";
 
}
 
}
Line 148: Line 181:
  
 
===Visual Basic===
 
===Visual Basic===
<pre>
+
<pre class="vb">
 
Dim objFileSystem as Object
 
Dim objFileSystem as Object
 
'Dim objFileSystem as FileSystemObject if you have added
 
'Dim objFileSystem as FileSystemObject if you have added
Line 163: Line 196:
  
 
Set objFileSystem = Nothing
 
Set objFileSystem = Nothing
</pre>
 
 
===Shell===
 
<pre>
 
test -f /foo/bar && echo "File exist"
 
 
</pre>
 
</pre>
  
Line 174: Line 202:
  
 
[[Category:C]]
 
[[Category:C]]
 +
[[Category:C++]]
 
[[Category:C sharp]]
 
[[Category:C sharp]]
 
[[Category:Common Lisp]]
 
[[Category:Common Lisp]]
Line 182: Line 211:
 
[[Category:Python]]
 
[[Category:Python]]
 
[[Category:Ruby]]
 
[[Category:Ruby]]
 +
[[Category:Seed7]]
 
[[Category:Tcl]]
 
[[Category:Tcl]]
 
[[Category:Visual Basic]]
 
[[Category:Visual Basic]]
 
[[Category:Shell]]
 
[[Category:Shell]]

Latest revision as of 04:16, 5 November 2010

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.