On Thu, 18 Dec 1997 20:19:16 +0100, Frank Heckenbach wrote:
Laurentiu COCEA wrote:
- How do I suspend I/O error messages in order to detect the
presence/absence of a file? In Turbo Pascal, one does this as follows:
{$I-} reset(file); {$I+} if IOResult <> 0 then...
Sorry, there's no {$I+-} directive in GPC yet, but some work has already been done towards implementing it.
As for checking if a file exists, there are other ways, e.g. searching the directory, or (at least under Un*x systems, I don't know if also under Dos) stat(2)ing the file. The following works on my Linux system, so it should be alright for you:
It is also possible to use gpc's built in extension to file binding that checks if a file exists, e.g. something like:
program pas(input, output);
var a : string(200);
function exists(filename: string) : Boolean; { Checks if a file exists. It returns positive if b.existing is TRUE or if the bind failed. The bind will fail for example if the name given is actually a directory name. }
var b : BindingType; f : bindable text; begin unbind(f); b := binding(f); b.name := filename; bind(f, b); b := binding(f); if b.bound then exists := b.existing else exists := TRUE; unbind(f); end; begin write('Enter a file name: '); readln(a); if exists(a) then writeln(a, ' exists.') else writeln(a, ' doesn''t exist.'); end.
The advantage is that you don't have to deal with any C-isms at all and it should work on any GPC platform without worrying about the underlying stat() implementation. The problem (as noted in the comments) is that if the bind fails it thinks the file exists, which is a bit of a kludge. However I couldn't get around the problem that appeared when a user gives a name that is used by a directory. Frank's code using stat() correctly reports true for directories.
-Kevin -- Kevin A. Foss --- kfoss@mint.net --