2011-07-26 33 views
1

我正在使用Boost FileSystem 3遍歷目錄中的某個文件,並且需要將文件名轉換爲char *作爲另一個lib,不幸的是我的C++ foo缺乏,可以有人幫忙嗎?將Boost FileSystem3迭代器強制轉換爲const char *

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; 
    } 

回答

2

*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; 

選擇你想使用的任何一個。首先閱讀文檔爲他們每個人的返回:

+1

鏈接也許應該去規範[提高文件系統的文件(http://www.boost.org/doc/ libs/1_47_0/libs/filesystem/v3/doc/reference.html#path-native-format-observers)在boost.org –

+0

這太好了,謝謝 – macarthy