将Boost FileSystem3迭代器转换为const char * [英] Casting a Boost FileSystem3 iterator to a const char*

查看:74
本文介绍了将Boost FileSystem3迭代器转换为const char *的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用Boost FileSystem 3遍历目录中的某些文件,并且需要将文件名强制转换为另一个库的char *,不幸的是我缺少C ++ foo,有人可以帮忙吗?

I'm looping over some file in a directory using Boost FileSystem 3 and I need to cast the filename to a char* for another lib, Unfortunately my C++ foo is lacking, can anyone help ?

  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的对象,因此您必须执行以下操作:

The expression*it returns an object of type path, so you've to this:

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

或者也许您想使用其他转换功能,如下所示:

Or maybe you want to use other conversion functions, as listed below:

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

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

Choose whichever you want to use. Read the documentation first as to what each of them returns:

这篇关于将Boost FileSystem3迭代器转换为const char *的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆