将文件内容复制到不是 char 类型的容器?
Copying file content to a container not type of char?
我的代码存在破坏性问题。我正在使用 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);
代码无法自行编译,仅由示例提供。
问题: 如何调用后面的copy函数
io::copy(inputFile, anotherInserter);
在以下场景下编译?我可以写一个提供类型转换的过滤器吗?
您可以从 io::file_descriptor_source
创建一个 std::istream
,然后使用其范围构造函数将 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
导致您的应用程序继续读取,直到内存耗尽。
我的代码存在破坏性问题。我正在使用 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);
代码无法自行编译,仅由示例提供。
问题: 如何调用后面的copy函数
io::copy(inputFile, anotherInserter);
在以下场景下编译?我可以写一个提供类型转换的过滤器吗?
您可以从 io::file_descriptor_source
创建一个 std::istream
,然后使用其范围构造函数将 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
导致您的应用程序继续读取,直到内存耗尽。