C ++中的文件路径

时间:2014-04-15 20:11:16

标签: c++ function ubuntu path directory

我正在尝试编写一个小程序,我需要在一个目录中获取文件的所有路径。

由于我的c ++知识有点受限,我不知道如何做到这一点。 所以我基本上在寻找一个适用于Ubuntu的代码。我需要将文件夹的路径作为参数,并获取包含此文件夹中所有文件路径的字符串的向量(或其他数据结构)。

这可能吗?如果是的话,你可以通过展示如何做到或者只是给我一个示例代码来帮助我吗?

1 个答案:

答案 0 :(得分:1)

您可能想要使用Boost Filesystem。更多DIY方法可能如下所示:

#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;
}

请注意,此方法还会将当前目录和父目录(路径&#34;。&#34;和#34; ..&#34;)放入向量中。此条目也可能无法以任何方式排序。