User Tools

Site Tools


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. Caution: In at least some versions of Windows 10 this does not work, and will return a non-zero value for a file as well as a directory. This appears to be a bug in Windows.

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. By using the website, you agree with storing cookies on your computer. Also you acknowledge that you have read and understand our Privacy Policy. If you do not agree leave the website.More information about cookies
checking_20whether_20a_20directory_20exists.txt · Last modified: 2019/04/25 23:42 by richardrussell