gpt4 book ai didi

c++ - 从函数返回 boost streambuf

转载 作者:太空宇宙 更新时间:2023-11-04 12:47:19 24 4
gpt4 key购买 nike

我正在尝试将读取 gz 文件的代码打包成一个函数,源代码取自 https://techoverflow.net/2013/11/03/c-iterating-lines-in-a-gz-file-using-boostiostreams/

我的尝试

boost::iostreams::filtering_streambuf<boost::iostreams::input> func(std::string filename);
boost::iostreams::filtering_streambuf<boost::iostreams::input> func(std::string filename)
{
std::ifstream file(filename, std::ios_base::in | std::ios_base::binary);
boost::iostreams::filtering_streambuf<boost::iostreams::input> inbuf;
inbuf.push(boost::iostreams::gzip_decompressor());
inbuf.push(file);
return inbuf;

}
void mymainfunc(std::string filename)
{

//Convert streambuf to istream
std::istream ifstrm( func( filename));
std::string line;
while(std::getline(ifstrm, line)) {
std::cout << line << std::endl;
}
}

如果不通过函数运行,代码运行良好,我认为我在返回类型中做错了。错误:https://pastebin.com/kFpjYG0M

最佳答案

流是不可复制的。事实上,这个filteringstreambuf甚至是不可移动的。

所以在这种情况下,您将希望通过智能指针动态分配和返回。然而,即使只返回过滤流缓冲区也不起作用,因为它会保存对 ifstream 的引用。那是本地人。

所以,也许您需要将其打包:

Live On Coliru

#include <boost/iostreams/filtering_streambuf.hpp>
#include <boost/iostreams/filter/gzip.hpp>
#include <fstream>

namespace bio = boost::iostreams;

struct MySource {
using fisb = bio::filtering_istreambuf;

struct State {
State(std::string filename) : ifs(filename, std::ios::binary) {
buf.push(bio::gzip_decompressor());
buf.push(ifs);
}

fisb buf;
std::ifstream ifs;
std::istream is { &buf };
};

std::unique_ptr<State> _state;

operator std::istream&() const { return _state->is; }
};

MySource func(std::string filename) {
auto inbuf = std::make_unique<MySource::State>(filename);
return {std::move(inbuf)};
}

#include <iostream>
void mymainfunc(std::string filename)
{
auto source = func(filename);
std::istream& is = source;

std::string line;
while(std::getline(is, line)) {
std::cout << line << std::endl;
}
}

int main(){
mymainfunc("test.cpp.gz");
}

选择#1

你可以简化它:

Live On Coliru

struct MySource {
struct State {
State(std::string filename) : ifs(filename, std::ios::binary) {
is.push(bio::gzip_decompressor());
is.push(ifs);
}

std::ifstream ifs;
bio::filtering_istream is;
};

std::unique_ptr<State> _state;

operator std::istream&() const { return _state->is; }
};

不单独处理流缓冲区使其更简单。

备选#2

不复制整个东西有其自身的优雅:

Live On Coliru

#include <boost/iostreams/filtering_stream.hpp>
#include <boost/iostreams/filter/gzip.hpp>
#include <fstream>
#include <iostream>

void mymainfunc(std::istream& is) {
std::string line;
while(std::getline(is, line)) {
std::cout << line << std::endl;
}
}

namespace bio = boost::iostreams;

int main(){
std::ifstream ifs("test.cpp.gz", std::ios::binary);

bio::filtering_istream is;
is.push(bio::gzip_decompressor());
is.push(ifs);

mymainfunc(is);
}

关于c++ - 从函数返回 boost streambuf,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50798805/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com