将文件内容复制到不是char类型的容器?

时间:2018-01-12 10:05:50

标签: c++ boost boost-iostreams

我的代码存在破坏性问题。我使用boost iostreams库将文件内容复制到由系统的其他组件提供的向量,因此我无法更改此容器的类型。我已经通过创建一个char类型的临时容器解决了这个问题,并且我将从这里创建内容到目标容器的副本。但是,我想知道没有临时容器可以解决问题吗?

请考虑以下代码。

namespace io = boost::iostreams;
namespace fs = boost::filesystem;

std::vector<char> container;
std::vector<unsigned char> anotherContainer;

auto inputFile = io::file_descriptor_source(fs::path(L"testfile.txt"));

auto inserter = io::back_inserter(container);
auto anotherInserter = io::back_inserter(anotherContainer);

io::copy(inputFile, inserter);
io::copy(inputFile, anotherInserter);

代码无法自行编译,仅由示例提供。

问题:如何进行后期复制功能调用

io::copy(inputFile, anotherInserter);

在以下场景中编译?我可以编写一个提供类型转换的过滤器吗?

1 个答案:

答案 0 :(得分:0)

您可以从std::istream创建io::file_descriptor_source,然后使用其范围构造函数将char读入矢量:

template<class IoDevice>
std::vector<unsigned char> read_all(IoDevice& io_device) {
    boost::iostreams::stream<IoDevice> io_stream(io_device);
    return std::vector<unsigned char>(
          std::istreambuf_iterator<char>{io_stream}
        , std::istreambuf_iterator<char>{}
        );
}

int main() {
    namespace io = boost::iostreams;
    namespace fs = boost::filesystem;
    auto inputFile = io::file_descriptor_source(fs::path(L"testfile.txt"));
    auto anotherContainer = read_all(inputFile);
}

请注意这种无条件读取整个文件的方法,因为恶意用户可以指示它读取/dev/zero,导致应用程序继续读取,直到内存不足为止。

相关问题