Enumerating folders with subfolders

Sometimes it is necessary to process files in a folders and all its subfolders. CorelSCRIPT has two functions to iterate through files/folders in a given folder: GETFIRSTFOLDER and GETNEXTFOLDER. Unfortunately they can't be used recursively to iterate through folders/subfolders. However it is still possible to achieve the same result with a little trick. In order to do this, it is necessary to store all the subfolders found in the current folder in an array and then start processing the subfolders as the enumeration in the current folder is completed. Here is the subroutine that does this.

In order for this subroutine to work, it is necessary to define the following variables at the beginning of the script body:

DECLARE SUB EnumerateFolders(StartFolder$)
GLOBAL Folders$(100)
GLOBAL Num&,ArraySize&
ArraySize&=100

Folders array will store the list of all folders/subfolders found. ArraySize indicates how many array items are allocated. If the number of folders found is greater, the array will be redimensioned and this variable value will be adjusted accordingly. Num indicates the number of folders found and stored in the array.

The subroutine itself is the following:

SUB EnumerateFolders(StartFolder$)
    Num&=0
    Ptr&=1
    Start$=StartFolder
    IF RIGHT(Start,1)<>"\" THEN Start=Start+"\"
    CurFolder=Start
    Num=Num+1
    Ptr=Ptr+1
    Folders(Num)=CurFolder
    f$=FINDFIRSTFOLDER(Start+"*.*",16+128)
    WHILE f$<>"" OR Ptr<=Num
        IF f$="" THEN
            CurFolder=Folders(Ptr)
            f$=FINDFIRSTFOLDER(CurFolder+"*.*",16+128)
            Ptr=Ptr+1
        ELSE
            IF f$<>"." AND f$<>".." THEN
                Num=Num+1
                IF Num>ArraySize THEN
                    ArraySize=ArraySize+50
                    REDIM PRESERVE Folders$(ArraySize)
                END IF
                Folders(Num)=CurFolder+f$+"\"
            END IF
            f$=FINDNEXTFOLDER()
        END IF
    WEND
END SUB

Here is an example of using this subroutine. This script allows to select the initital folder to start enumeration and then displays the list of all folders/subfolders in this folder:

Start$=GETFOLDER("")
IF Start="" THEN STOP
EnumerateFolders Start$
List$=""
FOR i&=1 TO Num
    List=List+Folders(i)
    IF i<>NUM THEN List=List+CHR(13)
NEXT i
MESSAGE List
STOP

[ CorelSCRIPT Tips&Tricks | Learning CorelSCRIPT | Oberon Home Page ]

Copyright 2000 by Alex Vakulenko. All rights reserved.
This page was last revised on 11/16/02.