【问题标题】:In c++11 passing a lambda function to scandir is probably impossible. What's the next best thing?在 c++11 中,将 lambda 函数传递给 scandir 可能是不可能的。下一个最好的事情是什么?
【发布时间】:2013-06-18 22:41:18
【问题描述】:

我需要一个实例方法或一个 lambda 函数,或者它相当于作为 select 函数参数传递给 scandir。有没有办法做到这一点?

我想要实现的关键是让选择函数(回调)看到调用它的类的每个实例的不同参数。为了使这个线程安全,或者只是不丑陋,我不能只将我的参数存储在一个全局变量中,这就是类实例的用途。

如果它在 c++11 中与 lambda 函数一起使用,它会是什么样子:

myclass:getFilesMatching(char startChar)
{
   ...
   mParam = startChar;
   auto lfunc = [this] (const struct dirent * dent) { return (*(dent->d_name) == mParam); };
   mNumFiles = scandir((char *)fullDirPath, &mfileList, lfunc, NULL);
}

这将获取名称以指定字符开头的所有文件。我不在乎我是否将局部变量或实例变量传递给函数。

我希望 scandir 本身是线程安全的。当然我可以使用信号量或互斥量,但这真的有必要吗?

当然这只是选择功能的一个简单例子。我真正想做的事情更复杂。

【问题讨论】:

    标签: c++11 lambda scandir instance-methods


    【解决方案1】:

    我不得不承认,我以前对scandir 或任何相关的 C 函数一无所知。但根据我通过阅读<dirent.h> 上的文档了解到的情况,它是一个辅助函数,用于包装对较低级别 APIS 的多次调用。

    在这种情况下,我更喜欢创建一个实现相同功能的 C++ 包装器,并使用类似 C++ 的 API。

    DIR 类型的包装器开始,以确保它被正确清理:

    namespace cpp {
    
        struct DIR { 
            ::DIR * dir;
    
            DIR(const std::string & path) : dir(opendir(path.c_str()))
            {
                if(dir==0) throw std::runtime_error("Unable to open path");
            }
    
            ~DIR() { if(dir!=0) closedir(dir); } 
    
            operator ::DIR * () { return dir; }
        };
    }
    

    scandir 函数现在可以这样实现:

    template<class Filter, class Compare>
    std::vector<dirent> scandir(const std::string & path, const Filter& filter, const Compare& compare) {
        cpp::DIR dir(path);
        std::vector<dirent> res;
        dirent entry, *entry_ptr = &entry;
        while( ::readdir_r(dir, &entry, &entry_ptr)==0 ) {
            if( entry_ptr==0 ) break;
            if( filter(entry) ) res.push_back(entry);
        }
    
        std::sort(begin(res), end(res), compare);
    
        return res;
    }
    

    然后这样称呼它:

    std::string path = ...;
    ...
    auto filter = [] (const dirent& entry) { return entry.d_name[0]!='.'; };
    auto compare = [](const dirent & lhs, const dirent & rhs) {
        return std::strcmp(lhs.d_name, rhs.d_name)<0; 
    };
    
    auto entries = cpp::scandir(path, filter, compare);
    

    readdir_r() 的使用使得上面的实现是线程安全的,尽管应该添加更多的检查来报告它返回的任何错误。

    注意:上面的代码需要包含以下标头:

    #include <dirent.h>
    #include <cstring>
    #include <algorithm>
    #include <iostream>
    #include <stdexcept>
    #include <vector>
    

    【讨论】:

      【解决方案2】:

      这就是我的工作:

      void with_file_names(const std::string &path,
                           std::function<void(const std::string& name)> action,
                           int(*filter)(const struct dirent *) = NULL)
      {
          struct dirent **namelist;
          auto nfiles = scandir(path.c_str(),
                                &namelist,
                                filter,
                                NULL);
          for (auto idx = 0; idx < nfiles; idx++) 
          {
              auto n = namelist[idx];
              action(std::string(n->d_name, n->d_namlen));
          }
          free(namelist);
      }
      

      然后

      with_file_names("./downloaded",
                      [](const std::string &file_name){
                          auto fullname = std::string("./downloaded/") + file_name;
                          // do something...
                      },
                      [](const struct dirent *pentry) {
                          return (int)(::strncmp("node-", pentry->d_name, 5) == 0);
                      });
      

      注意过滤器参数是一个 lambda。希望对您有所帮助!

      【讨论】:

      • 我认为你错过了问题的重点,你不能使用 lambda 函数将参数传递给过滤函数,所以这并没有真正的帮助。
      • @Étienne 这很有趣,因为它几乎有帮助 - 他正在使用非捕获 lambda(实际上可以转换为函数指针,因此理论上是 scandir 的有效操作数) 但是使用std::function 作为对话者完全破坏了这种可能性。将std::function 更改为std::add_pointer_t(从type_traits)实际上可能有效(我得到了与scandir 类似的东西)。
      • 我在 FileZilla 的修改版本上使用过它,所以我可以说它按描述工作。
      【解决方案3】:

      我还尝试将scandir 与 lambda 表达式结合,得到了一个有趣的结果:看起来有一个漏洞(可能是版本和编译器特定的错误),它允许从以下代码生成一个工作可执行文件, 使用 gcc (Debian 4.9.2-10)。

      #include <iostream>
      #include <dirent.h>
      #include <cstring>
      using std::cout;
      using std::endl;
      
      char *ext;
      unsigned int lext;
      
      int main (int argc, char **argv)
      {
          struct dirent **listing;
          ext = argv[2];
          lext = strlen (ext);
          int n = scandir (argv[1],
                           &listing,
                           [ext , lext] (const struct dirent *ent) -> int
                           {
                              // Select only files with extension EXT
                              auto lon = strlen (ent->d_name);
                              return (lon > lext  and
                                       !strcmp (ent->d_name + (lon-lext), ext))
                                  ? 1 : 0;
                           },
                           alphasort);
          if (n==-1)
          {
              cout << "scandir has failed" << endl;
              return 1;
          }
          else {
              cout << "scandir has found "<< n <<" matching entries.\n";
              for (int i=0 ; i<n ; ++i)
                  cout << i+1 << " - "<< listing[i]->d_name << "\n";
              return 0;
          }
      }
      

      如果您尝试更正捕获列表变量的范围,使其成为块本地,它将拒绝编译并出现以下错误:

      错误:无法将参数 '3' 的 'main(int, char**)::' 转换为 'int ()(const dirent)' 到 'int scandir(const char*, dirent***, int ()(const dirent), int (*)(const dirent**, const dirent**))'

      这似乎意味着可能将 lambda 编译为函数,因此可以以一种可行的方式将指向它的指针提供给 scandir。但是,我更喜欢其他 2 个答案的 C++ 方法。

      我不知道这是否应该被视为编译器错误。

      【讨论】:

      猜你喜欢
      • 2011-11-12
      • 2018-09-03
      • 1970-01-01
      • 2014-08-09
      • 2021-12-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-08-28
      相关资源
      最近更新 更多