Path: utzoo!utgpu!news-server.csri.toronto.edu!cs.utexas.edu!usc!rpi!uupsi!cmcl2!adm!news From: CDCKAB%EMUVM1.BITNET@cunyvm.cuny.edu ( Karl Brendel) Newsgroups: comp.lang.pascal Subject: FileExists (was Re: Cursor On/Off Code plus ...) Message-ID: <26609@adm.brl.mil> Date: 19 Apr 91 16:00:46 GMT Sender: news@adm.brl.mil Lines: 69 In article <15647@dutrun.UUCP>, winfave@dutrun.uucp (Alexander Verbraeck) wrote: >The FileExists function as posted in the "Cursor On/Off Code Plus" >posting (originating from Dave Sisson) contains a slight but >extremely boresome error, as far as I can see. My first attempt to >write a FileExists function contained the same error, and it took me >quite a while to find it. The original FE routing looked something >like: [...deleted...] >afterward. What's the flaw? Not closing the file in FileExists, which >occupies a DOS file handler when it exists. What's the solution? Either >always closing the file between the {$I-} and {$I+} directives, or >closing it after testing if IOresult reports that the file exists and >THEN closing the file. >I used the first method, resulting in the following function: > >function FileExists(fn:string) : boolean; > >var > f : text; > >begin > {$I-} > assign(f,fn); > reset(f); > close(f); > FileExists:=(IOresult=0); > {$I+} >end; (Alexander Verbraeck's posting provides an opportunity to discuss a FileExists function. My posting should in no way be taken as a criticism of his excellent discussion or of his particular coding.) FileExists functions seem to be enjoying a spurt of popularity on the net for some reason. :) As Alexander Verbraeck has pointed out, some popular FileExists functions may have unexpected results. They may also fail unexpectedly. E.g., if no file handles are available, Reset will fail, and a Reset-based function will return False. (Does one ever want to know if a file exists without caring if it can be opened. Yes. One example is a network semaphore.) Consider the use of FindFirst for a FileExists function. It works without requiring a file handle, and can easily be used to check the existance of directories, volume IDs, etc.: uses DOS; function FileExists(var fn : string; attr : word) : Boolean; var sr : SearchRec; begin {Exists} FindFirst(fn,attr,sr); FileExists := DosError = 0; end; {Exists} If you want this strictly for determining whether "real" files exist, you can drop attr from the parameters and include an appropriate value in the body of the function. +====================================================================+ | Karl Brendel Centers for Disease Control | | Internet: CDCKAB@EMUVM1.BITNET Epidemiology Program Office | | Bitnet: CDCKAB@EMUVM1 Atlanta GA 30093 USA | | Home of Epi Info 5.0 | +====================================================================+