in c++ how do i pull up (into a string) a random file in a f

Programming, for all ages and all languages.
Post Reply
Scarberry

in c++ how do i pull up (into a string) a random file in a f

Post by Scarberry »

lets say i have a folder and in it r 300 different files. i was wondering how i could pull up the filename of one of thoes files at random. all this in c++. (Dev-C++ to be spacific)


thanks
Tim

Re:in c++ how do i pull up (into a string) a random file in

Post by Tim »

1. Obtain a list of files
2. Select a random file from the list

Some quick code: (can't guarantee this will be correct)

Code: Select all

HANDLE find;
std::vector<std::string> files;
WIN32_FIND_DATA fd;

find = FindFirstFile("*", &fd);
if (find != INVALID_HANDLE_VALUE)
{
    do
    {
        files.push_back(fd.cFileName);
    } while (FindNext(find, &fd));
    FindClose(find);
}

if (files.empty())
    printf("No files found\n");
else
    printf("File is %s\n", files[rand() % files.size()].c_str());
Post Reply