无法读取文件进行文件处理,使用boost库获取文件路径

时间:2015-12-16 18:25:42

标签: c++ boost

ifstream my_file;
for (boost::filesystem::recursive_directory_iterator end, dir("F:/mails"); dir != end; ++dir) {
    if (dir->path().extension() != ".txt")
      continue;                                                        

    std::cout << *dir << "\n";                                         
    std::cout << dir->path().filename() << "\n";                        
    my_file.open(*dir);
    //rest of the code
 }

当我尝试使用上面的方法打开.txt文件时,编译器提供以下内容

error at "my_file.open(*dir);"... maybe some casting issue.
error C2664: 'void std::basic_ifstream<char,std::char_traits<char>>::open(const char *,std::ios_base::open_mode)' : cannot convert argument 1 from 'boost::filesystem::directory_entry' to 'const wchar_t *'    

2 个答案:

答案 0 :(得分:2)

std::fstream仅接受const char*作为路径名参数(以及{CES 11后的std::string)。所以你应该使用c_str()native() methods将路径对象转换为字符串:

for (boost::filesystem::recursive_directory_iterator end, dir("F:/mails");
     dir != end; ++dir
) {
    if (dir->path().extension() != ".txt")
        continue;
    ...
    my_file.open(dir->path.c_str()); // or better dir->path.native(), but this requires C++11
    ...
}

答案 1 :(得分:0)

我终于找到了解决方案

my_file.open(boost::filesystem::canonical(*dir).string());