The following example uses dir( ) to store the file information for all the files and directories in the root directory of the current drive to the array aFiles. Then the array is searched to display only the directories in the array. Manifest constants to represent the columns are created with the #define preprocessor directive to make the code more readable.

#define ARRAY_DIR_NAME 1 // Manifest constants for columns returned by dir( )

#define ARRAY_DIR_SIZE 2

#define ARRAY_DIR_DATE 3

#define ARRAY_DIR_TIME 4

#define ARRAY_DIR_ATTR 5

aFiles = new Array( )

nFiles = aFiles.dir( "\*.*", "D" ) // Read all files and directories

nElement = 1 // Start looking at first element

do

   nElement = aFiles.scan( "....D", nElement ) // Look for next directory 

   if nElement > 0 // Display a match 

      ? aFiles[ nElement - ARRAY_DIR_ATTR + ARRAY_DIR_NAME ] 

      if nElement++ >= aFiles.size // Continue looking with next element 

         exit // Unless that was the last element 

      endif 

   endif 

until nElement == 0 // Until there's no match

To find all the matches in the array, you need to keep track of the last match. Here it’s kept in the variable nElement. It starts at one, the first element, and is used in the scan( ) call as the starting element parameter. The result of each search is stored back in nElement. If there’s a match, the directory name is displayed. Then nElement is incremented—otherwise scan( ) would match the same element again—and the loop continues.

A few subtleties are present in the example code. First, when incrementing nElement, it is compared with the size of the array. If the element number is equal to (or greater than, which it should never be, but it’s good defensive programming to test for it anyway) the size of the array, that means the last match was in the last element of the array. This is possible only because the file attribute is in the last column of the array. In this case, you don’t want to call scan( ) again, since the starting element number is higher than the highest element number and would cause an error. So you EXIT out of the loop instead.

The variable nElement is incremented after the comparison to the size of the array by using the postfix ++ operator. If nElement was pre-incremented, the comparison would be off, although the rest of the loop would work.

To display the directory name, the column number of the file attribute column is subtracted from the matching element number, and the column number for the file name column is added. This yields the element number of the file name in the same row as the matching file attribute. This would work for any combination of search or display columns.