Re: file check
- Posted by CChris Aug 04, 2008
- 825 views
jeremy said...
I benchmarked three different methods of checking the existence of a file:
function file_exists_dir(sequence filename) return sequence(dir(filename)) end function function file_exists_open(sequence filename) integer a = open(filename, "r") if a = -1 then return 0 end if close(a) return 1 end function constant lib = open_dll("kernel32.dll"), filea = "parser.e", fileb="no.txt" constant f_access = define_c_func(lib, "GetFileAttributesA", {C_POINTER}, C_INT) function file_exists_win(sequence filename) atom pFilename = allocate_string(filename) integer r = c_func(f_access, {pFilename}) free(pFilename) return r > 0 end function
file_exists_dir() and file_exists_open() were about the same. file_exists_win() was much faster.
With 2376 files (C:\Windows\System32):
Time dir : 0.000129 per Time open: 0.000126 per Time win : 0.000033 per
With 1 file (mocked directory)
Time dir : 0.000044 per Time open: 0.000034 per Time win : 0.000028 per
The test looked for one file that did exist and one file that did not. This is a common enough operation that I will make a function called file_exists and place it in std/filesys.e for 4.0. On Unix we will use the C function access(). On DOS, it will revert to the dir() or open() method.
Jeremy
DOS 5.0+ I believe has an int #21 call to see if a file exists, it may be jyst as fast. Look for high numbers (between #60 and #6F). I may be able to check later.
CChris