

/*      RECUR is a recursive descent subroutine to search
                directories and subs    with wildcard and path
                capabilities -> then pass the path name
                to a user supplied function called "subfunc".
                2 switches are presently supported: totals
                and subs for subdirectories.
*/

#include <dos.h>
#include <stdio.h>
#include <stdlib.h>
#include <malloc.h>
#include <string.h>

#define MAX_SUB 128

extern  void subfunc(char *path);

int recurs(char *path, int subs, int totals)
{
struct find_t *fib;
char *drive, *dir, *fname, *ext;
char *tmppath, *tmpdir;
char (*subfifoptr)[_MAX_FNAME];
char *subfifo;
int total = 0;
                        /* malloc so we don't blow up the stack */
fib = malloc(sizeof(struct find_t));
drive = malloc(_MAX_DRIVE);
dir = malloc(_MAX_DIR);
fname = malloc(_MAX_FNAME);
ext = malloc(_MAX_EXT);
tmpdir = malloc(_MAX_DIR);
tmppath = malloc(_MAX_PATH);

if (subs)
        {
/* if subs switch - do subdirectories first, RECURSIVELY */
        subfifo = *subfifoptr =
                                (char *)malloc(_MAX_FNAME * MAX_SUB);
        _splitpath(path, drive, dir, fname, ext);
        _makepath(tmppath, drive, dir, "*", "*");
        if (!_dos_findfirst(tmppath, _A_SUBDIR, fib))
                do
                        {
                        if (fib->name[0] != '.' && fib->attrib &
                                                                         _A_SUBDIR)
                                strcpy(*subfifoptr++, fib->name);
                        } while (!_dos_findnext(fib) && *subfifoptr <
                                         &subfifo[(_MAX_FNAME - 1) * MAX_SUB]);
        **subfifoptr = NULL;            /* terminate fifo */
        *subfifoptr = subfifo;  /* reset fifo pointer */
        while(**subfifoptr)             /* while not at the end */
                {
                strcpy(tmpdir, dir);
                _makepath(tmppath, drive, 
                                strcat(tmpdir, *subfifoptr++), fname, ext);
                total += recurs(tmppath, subs, totals);
                }
        free(subfifo);
        }

if (!_dos_findfirst(path, _A_NORMAL, fib))
        do
                {
                _splitpath(path, drive, dir, fname, ext);
                strcpy(tmppath, drive);
                strcat(tmppath, dir);
                subfunc(strcat(tmppath, fib->name));
                total++;
                } while (!_dos_findnext(fib));
if (totals)
        printf("\ntotal = %d\t%s files\n", total, path);

free(fib), free(drive), free(dir), free(fname);
free(ext), free(tmpdir), free(tmppath);
return total;
}
