1

我目前有基本上包含这些命令的代码:

std::string line;
std::getline(ifs, line);

ifs是一些std::ifstream。该代码有效。

我现在想对从另一个来源解压缩的数据使用相同的数据。基本上,我会读取我在某处缓冲的块,然后使用一个有点像fgetc. 这一切都有效,但将非 STL 与 STL 代码混合在一起。

我想做的是封装解压并提供一个迭代器,以便调用std::getline工作。我想那将是一个istream_iterator?这个类需要包含的最小值是多少?

更新:根据我得到的评论,以及http://www.voidcn.com/article/p-vjnlygmc-gy.html上的 streambuf 实现,我现在有了以下代码。作为测试用例,我使用了 zlib 压缩。代码不是很好,我很感激任何改进它的提示。

class gzip_streambuf: public std::streambuf
{
private: 
    gzip_streambuf(const gzip_streambuf &);      
    gzip_streambuf &operator= (const gzip_streambuf &);
public:
    explicit gzip_streambuf(gzFile h_, std::size_t buf_sz_ = 1024, std::size_t putback_sz_ = 2) :
        putback_sz(std::max(putback_sz_, std::size_t(1))),
        buffer(std::max(putback_sz_, buf_sz_ ) + putback_sz_),
        h(h_)
    {
        char *end = &buffer.front() + buffer.size();        
        setg(end, end, end);
    }
    ~gzip_streambuf() {}    
    bool error(void)
    {
        return gzerr;
    }

private:    
    int_type underflow()
    {
        if (gptr() < egptr())
            return traits_type::to_int_type(*gptr());
        char *base = &buffer.front();
        char *start = base;
        if (eback() == base) {
            std::memmove(base, egptr() - putback_sz, putback_sz); 
            start += putback_sz;
        }
        int n = gzread(h, start, buffer.size() - (start - base));
        if ( n < 0 )
            gzerr = true;                        
        if ( n <= 0)
            return traits_type::eof();
        setg(base, start, start + n);
        return traits_type::to_int_type(*gptr());
    }

private:
    bool gzerr = false;    
    gzFile h = nullptr;
    const std::size_t putback_sz;
    std::vector<char> buffer;
};


class gzip_istream: public std::istream
{    
public:
    gzip_istream() {};
    ~gzip_istream() { delete gzbuf; };

private:    
    gzip_istream(const gzip_istream  &);      
    gzip_istream &operator= (const gzip_istream &);

public:    
    void open( const char * filename) {
        if ( h = gzopen(filename, "rb") ) {
            delete gzbuf;
            if ( gzbuf = new gzip_streambuf(h) ) {
                set_rdbuf(gzbuf);
                clear();
            } else
                close();            
        } 
    }    
    void close() {
        if (h)
            gzclose( std::exchange(h, nullptr) );
        delete std::exchange(gzbuf, nullptr);
        set_rdbuf(nullptr);
    }        
    bool is_open(void) {
        return h != nullptr;
    }    
private:
    gzFile h = nullptr;
    gzip_streambuf *gzbuf = nullptr;
};

它可以按如下方式使用:

std::string line;
gzip_istream gin;
gin.open("file.gz");         
if (gin.good()) {    
    while (std::getline( gin, line)) 
        std::cout << line << std::endl;
    gin.close();
}

我曾尝试使用instd::unique_ptr中的gzip_streambuf成员gzip_istream,但由于缺少复制构造函数,所有尝试都失败了。我想摆脱新的/删除的东西,但不知道如何。

4

0 回答 0