【问题标题】:Get list of files with same extension and process them获取具有相同扩展名的文件列表并处理它们
【发布时间】:2017-08-31 12:42:29
【问题描述】:

我无法在这里实现最佳答案:How to get list of files with a specific extension in a given folder

我正在尝试获取目录 argv[2] 中的所有“.vol”文件,并对找到的每个文件进行一些批处理。我想将每个文件传递给 ParseFile 函数,该函数将字符串作为参数。

// return the filenames of all files that have the specified extension
// in the specified directory and all subdirectories
vector<string> get_all(const boost::filesystem::path& root, const string& ext, vector<boost::filesystem::path>& ret){
    if(!boost::filesystem::exists(root) || !boost::filesystem::is_directory(root)) return vector<string>();

    boost::filesystem::recursive_directory_iterator it(root);
    boost::filesystem::recursive_directory_iterator endit;

    while(it != endit)
    {
        if(boost::filesystem::is_regular_file(*it) && it->path().extension() == ext) ret.push_back(it->path().filename());
        ++it;
        cout << *it << endl; 
        return *ret;   // errors here
    }
}



... main function


if (batch) {
   vector<boost::filesystem::path> retVec;
   vector<boost::filesystem::path> volumeVec = get_all(boost::filesystem::path(string(argv[2])), string(".vol"), retVec);


// convert volume files in volumeVec to strings and pass to ParseFile
   ParseFile(volumeFileStrings);

}

我在使用 get_all 函数以及如何正确返回向量时遇到问题。

【问题讨论】:

  • 添加更多细节。 “我在使用 get_all 函数以及如何正确返回向量时遇到问题”-具体有什么问题?你试过什么?你得到了什么结果?你期待什么?此外,您应该以SSCCE 的形式提出您的问题,而不是“...主要功能”,以便其他人可以测试和重现您的结果/问题。
  • 我收到错误:'operator*' 不匹配(操作数类型是 'std::vector<:filesystem::path>')return * ret
  • 你为什么在while循环中间返回return *ret
  • 我认为如果你将 return 语句移到 while 循环之外你应该没问题。
  • 等等,我想我只需要将函数定义从向量 更改为向量<:filesystem::path>

标签: c++ vector boost


【解决方案1】:

将return语句更改为vector&lt;boost::filesystem::path&gt;并从函数的参数中删除ret,而是在函数中创建ret,如下所示:

vector<boost::filesystem::path> ret;

然后,您需要将 ret 的返回语句 return ret; 移动到 while 循环下方,以便将所有文件名附加到 ret

您的代码将如下所示:

vector<boost::filesystem::path> get_all(const boost::filesystem::path& root, const string& ext){
    if(!boost::filesystem::exists(root) || !boost::filesystem::is_directory(root)) return;

    boost::filesystem::recursive_directory_iterator it(root);
    boost::filesystem::recursive_directory_iterator endit;
    vector<boost::filesystem::path> ret;
    while(it != endit)
    {
        if(boost::filesystem::is_regular_file(*it) && it->path().extension() == ext) ret.push_back(it->path().filename());
        ++it;
        cout << *it << endl; 
    }
    return ret;
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-04-21
    • 2019-03-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多