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

标签 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 *'    

最佳答案

std::fstream仅接受 const char* 作为路径名参数(以及自 C++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
    ...
}

关于c++ - 无法读取文件进行文件处理,使用boost库获取文件路径,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34319435/

相关文章:

c++ - 使用 libc++ 在 Mac Yosemite 上访问 std::string 成员时出现链接错误

c++ - 更改计算器不计算便士

c++ - boost::circular_buffer 相当于文件?

c++ - 如何使用 MinGW 构建 Boost 1.55?

c++ - Boost python参数错误

C++ 使用模板 boost lexical_cast?

c++ - 按索引访问 map 值

c++ - 解构具有不完整类型的对象

c++ - 循环重复而不再次提示用户?

c++ - 使用 boost 查找目录空间详细信息