User Tools

Site Tools


This is an old revision of the document!

Checking whether a directory exists

by Richard Russell, May 2006, amended May 2010

It's easy to check whether a file exists: you just try to open it:

        DEF FNcheckfile(file$)
        LOCAL F%
        F% = OPENIN(file$)
        IF F% CLOSE #F%
        = F%

This function returns a non-zero value if the file exists and zero if not (strictly speaking it may also return zero if the file exists but is not accessible, but that's usually what is wanted).

To check for the existence of a directory (folder) you can use the fact that the 'virtual' file NUL exists in every directory:

        DEF FNcheckdir(dir$)
        LOCAL F%
        F% = OPENIN(dir$+"\NUL")
        IF F% CLOSE #F%
        = F%

This function returns a non-zero value if the directory exists and zero if not.

If you want to know whether a file or directory with a given name exists you can use a combination of the above functions. However an alternative is to use Windows API calls:

        DEF FNcheckdir(name$)
        LOCAL dir%, sh%
        DIM dir% LOCAL 317
        IF RIGHT$(name$)="\" THEN name$=LEFT$(name$)
        SYS "FindFirstFile", name$, dir% TO sh%
        IF sh%<>-1 SYS "FindClose", sh% ELSE = 0
        = 8 - (!dir% AND 16)

This function returns a negative value if a directory with the specified name exists, a positive value if a file of that name exists, and zero if neither a file nor a directory of that name exists.

This website uses cookies for visitor traffic analysis. By using the website, you agree with storing the cookies on your computer.More information
checking_20whether_20a_20directory_20exists.1523978282.txt.gz · Last modified: 2018/04/17 15:18 by tbest3112