Check that file exists: Difference between revisions
No edit summary |
add JScript |
||
Line 337: | Line 337: | ||
direxist 'docs' |
direxist 'docs' |
||
direxist '/docs'</lang> |
direxist '/docs'</lang> |
||
=={{header|Java}}== |
=={{header|Java}}== |
||
<lang java>import java.io.File; |
<lang java>import java.io.File; |
||
Line 356: | Line 357: | ||
} |
} |
||
}</lang> |
}</lang> |
||
=={{header|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> |
|||
=={{header|Logo}}== |
=={{header|Logo}}== |
Revision as of 20:26, 6 October 2009
![Task](http://static.miraheze.org/rosettacodewiki/thumb/b/ba/Rcode-button-task-crushed.png/64px-Rcode-button-task-crushed.png)
You are encouraged to solve this task according to the task description, using any language you may know.
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.
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>
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>
BASIC
<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>
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>
C
<lang c>#include <sys/types.h>
- include <sys/stat.h>
- include <unistd.h>
int main(){
struct stat file_stat; if(stat("/tmp/test",&file_stat) ==0) printf("file exists"); else printf("no file lol"); return 0;
}</lang>
C++
<lang cpp>
- include "boost/filesystem.hpp"
- include <string>
- 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>
Clojure
(import '(java.io File)) (doseq file (list (new File "input.txt") (new File "/input.txt")) (when (not (. file exists)) (println file "is missing")) (when (. file isDirectory) (println file "is a directory!"))) (doseq file (list (new File "docs") (new File "/docs")) (when (not (. file exists)) (println file "is missing")) (when (. file isDirectory) (println file "is a directory!"))
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.
<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.file, std.path: sep;
void verify(string name) {
if (name.exists()) writefln(name, " exists"); else writefln(name, " doesn't exist");
}
void main() {
// check in current working dir verify("input.txt"); verify("docs"); // check in root verify(sep~"input.txt"); verify(sep~"docs");
} </lang>
DOS 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>
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!` }) }
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
Fortran
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>
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"
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>
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>
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>
MAXScript
-- Here doesFileExist "input.txt" (getDirectories "docs").count == 1 -- Root doesFileExist "\input.txt" (getDirectories "C:\docs").count == 1
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>
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>
OCaml
<lang ocaml>Sys.file_exists "input.txt";; Sys.file_exists "docs";; Sys.file_exists "/input.txt";; Sys.file_exists "/docs";;</lang>
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 ther in the root dir';</lang>
Perl
<lang perl>use File::Spec::Functions qw(catfile rootdir);
- here
print -e 'input.txt'; print -d 'docs';
- 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";'
Pop11
sys_file_exists('input.txt') => sys_file_exists('/input.txt') => sys_file_exists('docs') => sys_file_exists('/docs') =>
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:
;;; 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;
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>
Python
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")
- 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)
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>
Ruby
<lang ruby>File.exist?("input.txt") File.exist?("/input.txt") File.exist?("docs") File.exist?("/docs")</lang>
Scheme
<lang scheme>(file-exists? filename)</lang>
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
[ "R" file.open dup 0 <> [ dup file.close ] ifTrue 0 <> ] is exists? " input.txt" exists? . " /input.txt" exists? . " docs" exists? . " /docs" exists? .
UNIX Shell
test -f input.txt test -f /input.txt test -d docs test -d /docs
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
'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"))
- Programming Tasks
- File System Operations
- Ada
- AutoHotkey
- BASIC
- C
- C++
- Boost
- C sharp
- Clojure
- Common Lisp
- CL-FAD
- D
- DOS Batch File
- E
- Forth
- Fortran
- Haskell
- J
- Java
- JScript
- Logo
- MAXScript
- Modula-3
- Objective-C
- OCaml
- PHP
- Perl
- Pop11
- PowerShell
- Python
- R
- Raven
- Ruby
- Scheme
- Slate
- Smalltalk
- Standard ML
- Tcl
- Toka
- UNIX Shell
- Vedit macro language
- Visual Basic .NET
- TI-83 BASIC/Omit
- TI-89 BASIC/Omit