gpt4 book ai didi

c++ - 我可以将 ftw 函数用于 C++ 中的类方法吗?

转载 作者:塔克拉玛干 更新时间:2023-11-03 01:15:08 24 4
gpt4 key购买 nike

我想使用 ftw-function递归遍历文件系统结构。此外,该方法应在类内部使用。此外,由 nftw() 调用的入口函数属于同一类。情况必须如此,因为入口函数应该更改某些类成员,具体取决于它找到的文件。

在实现这种方法时,出现错误(见下文)。这是语法问题还是甚至不可能将指向方法的指针转发给 nftw()?如果不可能,您是否知道在 Linux 下重新遍历文件系统结构的任何替代方法?

class model
{
public:
boost::unordered_map<std::string, int> map;

int configure(const char *name)
{
// ...
ftw("DTModels/", this->ftw_entry, 15);
// ...

return = 0;
}


private:

int ftw_entry(const char *filepath, const struct stat *info, const int typeflag)
{
// Here I want to change the member 'map'
std::string filepath_s = filepath;
std::cout << "FTW_Entry: " << filepath_s << std::endl;
}
};


ERROR:
a pointer to a bound function may only be used to call the function
ftw("DTModels/", this->ftw_entry, 15);

最佳答案

我已经很多年没有使用过 ftw 了,既然你要求替代,请看一下 std::filesystem (C++17)。许多 C++17 之前的安装都可以通过 boostexperimental 使用它。如果您使用 C++17 之前的实现之一,您可能需要从下面删除一些 stat 行以使其工作。

#include <iostream>

//#define I_HAVE_BOOST

#if __cplusplus >= 201703L
#include <filesystem>
namespace fs = std::filesystem;
#elif I_HAVE_BOOST
#include <boost/filesystem.hpp>
namespace fs = boost::filesystem;
#else
#include <experimental/filesystem>
namespace fs = std::experimental::filesystem;
#endif

auto& out = std::cout;

void show_dent(const fs::directory_entry& dent) {
static size_t indent=0;
std::string ind(indent, ' ');

fs::file_status lstat = dent.symlink_status();

if( fs::is_symlink(lstat) ) {
fs::path pp = fs::read_symlink(dent);
out << ind << dent << " -> " << pp << "\n";
++indent;
show_dent(fs::directory_entry(pp));
--indent;
} else {
if(fs::is_directory(dent)) {
fs::directory_iterator dit_end;

std::cout << "Directory " << dent << " includes the following files:\n";
++indent;
for(auto dit = fs::directory_iterator(dent); dit != dit_end; ++dit) {
show_dent(*dit);
}
--indent;
} else {
fs::file_status stat = dent.status();

out << ind << dent << "\n"
<< ind << " stat\n"
<< ind << " is_regular_file : " << fs::is_regular_file(stat) << "\n"
<< ind << " is_directory : " << fs::is_directory(stat) << "\n"
<< ind << " is_block_file : " << fs::is_block_file(stat) << "\n"
<< ind << " is_character_file: " << fs::is_character_file(stat) << "\n"
<< ind << " is_fifo : " << fs::is_fifo(stat) << "\n"
<< ind << " is_socket : " << fs::is_socket(stat) << "\n"
<< ind << " is_symlink : " << fs::is_symlink(stat) << "\n"
<< ind << " exists : " << fs::exists(stat) << "\n";
if( fs::is_regular_file(stat) ) {
out
<< ind << " file_size : " << fs::file_size(dent) << "\n";
}
}
}
}

int main(int argc, char* argv[]) {
std::vector<std::string> args(argv+1, argv+argc);

out << std::boolalpha;

for(const auto& file_or_dir : args) {
show_dent(fs::directory_entry(file_or_dir));
}

return 0;
}

关于c++ - 我可以将 ftw 函数用于 C++ 中的类方法吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53445524/

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