Question

I am trying to write a small program for which I need get all the paths for the files in one directory.

Since my c++ knowledge is a bit limited, I have no idea how to do this. So I am basically looking for a piece of code that will work for Ubuntu. I need to give the path of the folder as argument and get a vector(or another data structure) of strings containing all the file paths inside this folder.

Is this possible? If yes, can you help me by showing how to do it or can just give me a sample code?

Was it helpful?

Solution

You might want to use Boost Filesystem. A more DIY approach could look like this:

#include <string>
#include <vector>

#include <dirent.h>
#include <sys/types.h>

std::vector<std::string> readDirectory(std::string path)
{
    std::vector<std::string> result;
    auto dp = opendir(path.empty() ? "." : path.c_str()); // use current directory if path is empty
    if(dp != nullptr)
    {
        while(true)
        {
            auto de = readdir(dp);

            if(de == nullptr)
                break; // all entries have been read, stop parsing

            std::string entry(de->d_name);
            result.push_back(entry);
        }
        closedir(dp);
    }

    return result;
}

Note that this approach will also put the current directory and the parent directory (paths "." and "..") into the vector. Also the entries might not be sorted in any way.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top