将 boost::filesystem 与 std::ifstream 一起使用?

问题描述 投票:0回答:2

我正在使用带有 C++ 20 和 boost 1.71.0 的 Ubuntu 20.04 LTS。

以下编译无误并输出示例文件内容:

#include <iostream>
#include <string>
#include <boost/filesystem.hpp>
#include <filesystem>

int main() {
    boost::filesystem::path output_dir = boost::filesystem::path("/out/");
    boost::filesystem::path sample_file = output_dir / "sample.txt";
    std::ifstream ifs{sample_file};
    std::string content((std::istreambuf_iterator<char>(ifs)), (std::istreambuf_iterator<char>()));
    std::cout << "Sample file content: " << std::endl << content << std::endl;
    return 0;
}

那么这是如何运作的呢?这是

boost::filesystem::path
隐式转换为
std::string
吗?

使用安全吗?

c++ boost iostream
2个回答
2
投票

Boost Filesystem fstream的文档表明:

C++ 标准库的标头使用

const char*
来传递表示文件名的参数,该用法出现了七次。

文件系统库的

fstream.hpp
标头在命名空间
boost::filesystem
中提供等效组件,但七个
const char*
参数已被
const path&
参数替换。

文件系统库的

fstream.hpp
标头仅使用标准库组件作为基类,然后重新声明构造函数和打开函数以采用
const path&
类型而不是
const char*
类型的参数。

其使用记录在2 分钟教程示例中。


0
投票

std::basic_fstream
有一个构造函数,它采用模板化的
FSPath
类型https://en.cppreference.com/w/cpp/io/basic_ifstream/basic_ifstream

这个重载应该只接受

std::filesystem::path
,但看起来像libstdc++接受任何符合std::filesystem::path接口的类
。这是非标准的,不能与其他标准库一起编译:
https://godbolt.org/z/njr5s3har

您可以使用

boost/filesystem/fstream.hpp

 标题修复此问题,但您必须将 std::ifstream
 更改为 
boost::filesystem::fstream
。更好的解决方法是改用 
std::filesystem
,这主要是 
boost::filesystem
 的替代品。

© www.soinside.com 2019 - 2024. All rights reserved.