gpt4 book ai didi

c++ - 将 Boost FileSystem3 迭代器转换为 const char*

转载 作者:可可西里 更新时间:2023-11-01 18:39:18 25 4
gpt4 key购买 nike

我正在使用 Boost FileSystem 3 循环遍历目录中的一些文件,我需要将文件名转换为 char* 以用于另一个库,不幸的是我的 C++ foo 缺失,任何人都可以帮忙吗?

  int main(int argc, char* argv[])
{
path p (argv[1]); // p reads clearer than argv[1] in the following code

try
{
if (exists(p)) // does p actually exist?
{
if (is_regular_file(p)) // is p a regular file?
cout << p << " size is " << file_size(p) << '\n';

else if (is_directory(p)) // is p a directory?
{
cout << p << " is a directory containing:\n";

typedef vector<path> vec; // store paths,
vec v; // so we can sort them later

copy(directory_iterator(p), directory_iterator(), back_inserter(v));

sort(v.begin(), v.end()); // sort, since directory iteration
// is not ordered on some file systems

for (vec::const_iterator it (v.begin()); it != v.end(); ++it)
{
cout << " " << *it << '\n';
/****************** stuck here **************************/
// I need to cast *it to a const char* filename
/****************** stuck here **************************/
}
}

else
cout << p << " exists, but is neither a regular file nor a directory\n";
}
else
cout << p << " does not exist\n";
}

catch (const filesystem_error& ex)
{
cout << ex.what() << '\n';
}

return 0;
}

最佳答案

表达式*it 返回类型为path 的对象,因此您必须这样做:

const std::string & s = (*it).string(); 
const char *str = s.c_str(); //this is what you want

或者您可能想使用其他转换函数,如下所列:

const std::string & string() const;
std::string native_file_string() const;
std::string native_directory_string() const;

选择您要使用的任何一个。首先阅读文档,了解它们各自返回的内容:

关于c++ - 将 Boost FileSystem3 迭代器转换为 const char*,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6826310/

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