【问题标题】:Sorted directory listing using pattern regexp matching使用模式正则表达式匹配的排序目录列表
【发布时间】:2011-07-13 14:23:06
【问题描述】:

我使用以下代码 sn-p 使用 boost-filesystem 和 boost-regexp 从作为参数输入的目录中获取绝对路径+文件名而感到内疚。

其中input_dir 是包含命令行参数的变量,表示要遍历的目录的名称,

  string dir_abs_name = "./" + input_dir;
  string file_abs_name;
  path current_dir(dir_abs_name);
  boost::regex pattern("m.*"); // list all files starting with m

  for (directory_iterator iter(current_dir),end; iter!=end; ++iter) {
    string name = iter->path().leaf();
    if (regex_match(name, pattern)) {
      file_abs_name = dir_abs_name + name;
      input_file = str_to_char(file_abs_name); // my own function that converts string to char* (needed that for another method later on in the code)

      std::cout << "--> considering file " << input_file << "... \n";
    }
  }

现在我面临的问题是列表不是按字母顺序排列的。我得到随机匹配,而不是按任何特定顺序。有没有办法强制执行该字母顺序?

谢谢。

编辑:值得一提的是,在程序中,我有时只处理目录中整个文件列表的一个子集。当我传递一个参数以进行选择时,我会这样做,假设目录中的 1000 个文件中只有 4 个文件。可以在检索列表后对它们进行排序..但检索仍然是随机的。

【问题讨论】:

    标签: c++ regex sorting boost filesystems


    【解决方案1】:

    为什么不将结果缓存在 (std::vector) 中,对向量进行排序,然后遍历排序后的向量以执行处理?

    例如:

    string dir_abs_name = "./" + input_dir;
    string file_abs_name;   
    path current_dir(dir_abs_name);   
    boost::regex pattern("m.*"); // list all files starting with m
    std::vector<std::string> accumulator;
    for (directory_iterator iter(current_dir),end; iter!=end; ++iter) {     
        string name = iter->path().leaf();
        if (regex_match(name, pattern)) {
           file_abs_name = dir_abs_name + name; 
           accumulator.push_back(file_abs_name);
        }   
    }
    std::sort(accumulator.begin(), accumulator.end());
    std::vector<std::string>::iterator iter;
    for (iter = accumulator.begin(); iter != accumulator.end(); ++iter) {
        char* input_file = str_to_char(*iter); // my own function that converts string to char* (needed that for another method later on in the code)                            
        std::cout << "--> considering file " << input_file << "... \n"; 
    }
    

    【讨论】:

    • 这会解决它,是的,但我正在寻找一种按顺序进行正则表达式匹配的方法。在程序中,我有时只处理整个文件列表的一个子集。当我传递一个参数以进行选择时,我会这样做,假设目录中的 1000 个文件中只有 4 个文件。即使您的修改会使它们排序.. 它们本身仍然会被随机选择(例如;它们仍然是 12、22、84 和 96,而不是 1、2、3、4)。
    • 我建议使用std::set 而不是std::vector,因为一组总是有序的。只需插入到集合中,然后对其进行迭代
    • Aarohi,所以我理解问题的方式是您现在需要能够从一个目录或一组目录中选择前(按字母顺序)n 个文件。如果是这种情况,您需要: 1 - 更改迭代文件系统的方式。 2 - 仍然使用上面的过程,但是在排序后从向量中选择前四个。显然,第二种解决方案需要索引输入集中的所有文件 - 因此也许更聪明的人可以帮助您解决解决方案 1。
    猜你喜欢
    • 1970-01-01
    • 2022-07-28
    • 1970-01-01
    • 2013-10-23
    • 2012-06-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多