The ScanDir class (See Figure 3.5) is derived from the FileStat class, and is the wrapper class for the scandir() routine, which obtains the entries of a directory in file systems.
The constructor takes two parameters - the path and the wildcard for the entries. It checks if the path is a directory, and then calls the scandir() routine to obtain the table of the entries.
Although the routine itself has the mechanism for wildcard searching, the mechanism is not compatible with non-static member functions, which take hidden this pointers. Instead, this class utilizes the encapsulated regular expression class Regex from libg++ to realize wildcard searching.
The operation entries() returns the total number of the entries matching the wildcard. This operation is not efficient in the counting because the scandir() routine is invoked with no wildcards and the matching entries must be checked one by one. However, the calculated total number is stored in the member entry and used for prompt response next time.
The object has the internal state for obtaining the entries. The member index contains the index in the namelist array for searching the next entry. The operation initFilter() resets the index as 0 in order to rewind the searching. The operation getNextEntry() returns the next matching entry. It returns null when there are no more entries.
The following is a sample usage of the class.
ScanDir dir(".", ".*\\.tex"); // *.tex files in the current directory const char *entry; dir.initFilter(); while ((entry = dir.getNextEntry()) != 0) cout << entry << endl;
The wildcard matches only when the whole file name matches the regular expression.