gpt4 book ai didi

c++11 - 在 c++11 中,将 lambda 函数传递给 scandir 可能是不可能的。下一个最好的事情是什么?

转载 作者:行者123 更新时间:2023-12-03 03:04:14 25 4
gpt4 key购买 nike

我需要一个实例方法或 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 本身是线程安全的。当然,我可以使用信号量或互斥体,但这真的有必要吗?

当然这只是select函数的一个简单例子。我实际上想做的事情更复杂。

最佳答案

我必须承认我之前对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()使上面的实现是线程安全的,尽管应该添加更多检查来报告它返回的任何错误。

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

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

关于c++11 - 在 c++11 中,将 lambda 函数传递给 scandir 可能是不可能的。下一个最好的事情是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17241347/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com