I am working on a game, and I need a program that will find random filenames from about the system. I am unsure as to how I should go about it.
Here is what I have so far: Note, I need help with the get_random_files function. I don't exactly know how to grab random files in a quick and memory extensive way.
char islld(char *path)
{
DIR *d = opendir(path);
struct dirent *ds;
struct stat st;
char *buf = malloc(strlen(path) + 1024), ret = -1;
while ((ds = readdir(d)) != NULL)
{
sprintf(buf, "%s/%s", path, ds->d_name);
stat(buf, &st);
if (S_ISDIR(st.st_mode))
goto err;
}
ret = 1;
err:
ret = ret < 0 ? 0 : ret;
closedir(d);
free(buf);
return ret;
}
char hasfiles(char *path)
{
DIR *d = opendir(path);
struct dirent *ds;
struct stat st;
char *buf = malloc(strlen(path) + 1024);
while ((ds = readdir(d)) != NULL)
{
sprintf(buf, "%s/%s", path, ds->d_name);
stat(buf, &st);
if (S_ISREG(st.st_mode))
{
free(buf);
closedir(d);
return 1;
}
}
free(buf);
closedir(d);
return 0;
}
tlist *getdirs(char *path)
{
tlist *ret = tlist_init();
DIR *d = opendir(path);
struct dirent *ds;
struct stat st;
char *buf = malloc(strlen(path) + 1024);
while ((ds = readdir(d)) != NULL)
{
sprintf(buf, "%s/%s", path, ds->d_name);
stat(buf, &st);
if (S_ISDIR(st.st_mode))
tlist_insert(ret, buf, (unsigned int)strlen(buf) + 1);
}
free(buf);
closedir(d);
return ret;
}
tlist *getfiles(char *path)
{
tlist *ret = tlist_init();
DIR *d = opendir(path);
struct dirent *ds;
struct stat st;
char *buf = malloc(strlen(path) + 1024);
while ((ds = readdir(d)) != NULL)
{
sprintf(buf, "%s/%s", path, ds->d_name);
stat(buf, &st);
if (S_ISREG(st.st_mode))
tlist_insert(ret, buf, (unsigned int)strlen(buf) + 1);
}
free(buf);
closedir(d);
return ret;
}
tlist *get_random_files(char *basepath, int num)
{
tlist *dirs = NULL, *files = NULL, *retfiles = tlist_init();
char buf[4096]; //should be plenty
int i, j, nf;
strcpy(buf, basepath);
for (nf = 0; nf < num;)
{
if (files == NULL) files = tlist_init();
if (dirs == NULL)
{
if (!islld(buf))
if (hasfiles(buf))
files = getfiles(buf);
}
}
return NULL;
}
I don't know if I need to just completely scrap that whole thing, but I am in need of assistance in completing the get_random_files function. For reference, here is my tlist definition:
struct typelesslist_node
{
void *data;
struct typelesslist_node *next;
unsigned int size;
};
typedef struct typelesslist_node tlist;
tlist * tlist_init(void);
void tlist_insert(tlist *list, void *data, unsigned int size);
tlist * tlist_remove(tlist *list, unsigned int key);
void tlist_get(tlist *list, void *dest, unsigned int key);
tlist * tlist_free(tlist *list);
void tlist_insert_list(tlist *dest, tlist *src);
again, any help at all is much appreciated. I would like to steer away from things like C++, boost, etc. My hopes are that this program doesn't depend on any external libraries.
Thanks.