Here is how I have implemented it some long time ago, although it solves the problem at hand within two "sweeps" (and not one, as you might have been aiming for in your question):
#include <io.h>
#include <stdlib.h>
#include <string.h>
typedef struct
{
int fileCount; //The number of files in the current directory
char* fileIsDir; //An array of sub-dir flags (for each file)
char** fileNames; //An array of names (for each file)
}
Directory;
void Open(Directory* directory)
{
int fileCount = 0;
char* fileIsDir = 0;
char** fileNames = 0;
int i;
int handle;
struct _finddata_t file;
handle = _findfirst("*.*",&file);
while (_findnext(handle,&file) == 0)
fileCount++;
_findclose(handle);
fileIsDir = (char* )malloc(fileCount*sizeof(char ));
fileNames = (char**)malloc(fileCount*sizeof(char*));
handle = _findfirst("*.*",&file);
for (i=0; i<fileCount; i++)
{
_findnext(handle,&file);
fileIsDir[i] = (file.attrib&_A_SUBDIR)!=0;
fileNames[i] = (char*)malloc(strlen(file.name)+1);
strcpy(fileNames[i],file.name);
}
_findclose(handle);
directory->fileCount = fileCount;
directory->fileIsDir = fileIsDir;
directory->fileNames = fileNames;
}
void Close(Directory* directory)
{
int fileCount = directory->fileCount;
char* fileIsDir = directory->fileIsDir;
char** fileNames = directory->fileNames;
int i;
for (i=0; i<fileCount; i++)
free(fileNames[i]);
if (fileNames)
free(fileNames);
if (fileIsDir)
free(fileIsDir);
}