Q(uick)BASIC Function: DIR$

Quick View

DIR$

Returns a filename that matches the specified pattern

Worth knowing

Useful and cross-version information about the programming environments of QBasic and QuickBasic.

Syntax
  • DIR$[(filespec$)]
Description/Parameter(s)
  • BASIC generates the error message, "Illegal Function Call" if you don't specify a filespec$ when you first call DIR$.

Usage Notes

  • DIR$ returns the first filename that matches the filespec$ you specify. To retrieve additional filenames that match the filespec$ pattern, call DIR$ again with no argument. When no filenames match, DIR$ returns a null string.
  • You do not have to retrieve all the filenames that match a given filespec$ before calling DIR$ again with a new filespec$.
  • DIR$ is not case sensitive. "C" is the same as "c".

Programming Tips

  • Because filenames are retrieved in no particular order, you may want to store filenames in a dynamic array and sort the array.
Example

This example uses the DIR$ function within the GetFileCount FUNCTION procedure to return the number of files that match the given file specification.

DECLARE FUNCTION GetFileCount& (filespec$) filespec$ = "*.*" count = GetFileCount(filespec$) PRINT count; "files match the file specification." FUNCTION GetFileCount& (filespec$) 'This function evaluates a file specification and returns the 'number of files that match the specification. Wild card characters '("*" and "?") are permitted. Drive and directory path specifications 'may also be included in filespec$. DIM FileCount AS LONG IF LEN(DIR$(filespec$)) = 0 THEN 'Ensure filespec is valid. FileCount& = 0 'It's not. ELSE FileCount = 1 'It is, so count files. DO WHILE LEN(DIR$) > 0 FileCount& = FileCount& + 1 LOOP END IF GetFileCount = FileCount& END FUNCTION

See also: