Get an istream from a char*

Get an istream from a char*

本文关键字:char from an istream Get      更新时间:2023-10-16

我有一个char*和从库接收的数据长度,我需要将数据传递给一个接受istream的函数。

我知道我可以创建一个stringstream,但这将复制所有的数据。而且,数据肯定会有0,因为它是一个zip文件,创建一个字符串流将采取数据,直到第一个0我认为。

有没有办法创建一个istream从char*和它的大小不复制所有的数据?

这是一个在网上找到的未弃用的方法,您是否派生了自己的std::streambuf类,但简单且似乎有效:

#include <iostream>
#include <istream>
#include <streambuf>
#include <string>
struct membuf : std::streambuf
{
    membuf(char* begin, char* end) {
        this->setg(begin, begin, end);
    }
};
int main()
{
    char buffer[] = "I'm a buffer with embedded nullsand linen feeds";
    membuf sbuf(buffer, buffer + sizeof(buffer));
    std::istream in(&sbuf);
    std::string line;
    while (std::getline(in, line)) {
        std::cout << "line: " << line << "n";
    }
    return 0;
}
输出:

line: I'm a buffer with embedded nullsand line
line:  feeds

使用Boost的非弃用解决方案:

#include <boost/iostreams/stream.hpp>
#include <boost/iostreams/device/array.hpp>
using namespace boost::iostreams;
basic_array_source<char> input_source(my_ptr_to_char, byte_count);
stream<basic_array_source<char> > input_stream(input_source);

或者更简单:

#include <boost/interprocess/streams/bufferstream.hpp>
using namespace boost::interprocess;
bufferstream input_stream(my_ptr_to_char, byte_count);

唯一(简单)可移植的方法包括:

std::istringstream ss(std::string(buf,len));

实际上,这可能会复制数据两次,一次创建string,一次创建istringstream。(也许c++ 11可以通过move构造函数避免其中一个拷贝;我不确定。

然而,如果你足够幸运,你的c++实现将允许你这样做:

std::istringstream ss;
ss.rdbuf()->pubsetbuf(buf,len);

在GNU c++(以及,我相信,其他一些实现)下,这将在不复制数据的情况下创建stringstream。但根据规范,这是"实现定义"的行为(参见此问题)。

通过包含len参数,您可以确保这两种方法都不会出现null字符的问题。

唯一可移植的方法是实现自己的stringbuf的子类,并使用它来初始化stringstream。不适合胆小的人。

我需要一个支持tellgseekg且不需要boost的解决方案。

char_array_buffer来自编写自定义流缓冲区(std::streambuf)的初学者指南,给出了一个好的起点。

byte_array_buffer.h:

#include <cstdio>
#include <string>
#include <list>
#include <fstream>
#include <iostream>
//
// http://www.mr-edd.co.uk/blog/beginners_guide_streambuf
//
class byte_array_buffer : public std::streambuf
{
public:
    byte_array_buffer(const uint8_t *begin, const size_t size);
private:
    int_type underflow();
    int_type uflow();
    int_type pbackfail(int_type ch);
    std::streamsize showmanyc();
    std::streampos seekoff ( std::streamoff off, std::ios_base::seekdir way,
                            std::ios_base::openmode which = std::ios_base::in | std::ios_base::out );
    std::streampos seekpos ( std::streampos sp,
                            std::ios_base::openmode which = std::ios_base::in | std::ios_base::out);
    // copy ctor and assignment not implemented;
    // copying not allowed
    byte_array_buffer(const byte_array_buffer &);
    byte_array_buffer &operator= (const byte_array_buffer &);
private:
    const uint8_t * const begin_;
    const uint8_t * const end_;
    const uint8_t * current_;
};

byte_array_buffer.cpp:

#include "byte_array_buffer.h"
#include <cassert>

byte_array_buffer::byte_array_buffer(const uint8_t *begin, const size_t size) :
begin_(begin),
end_(begin + size),
current_(begin_)
{
    assert(std::less_equal<const uint8_t *>()(begin_, end_));
}
byte_array_buffer::int_type byte_array_buffer::underflow()
{
    if (current_ == end_)
        return traits_type::eof();
    return traits_type::to_int_type(*current_);
}
byte_array_buffer::int_type byte_array_buffer::uflow()
{
    if (current_ == end_)
        return traits_type::eof();
    return traits_type::to_int_type(*current_++);
}
byte_array_buffer::int_type byte_array_buffer::pbackfail(int_type ch)
{
    if (current_ == begin_ || (ch != traits_type::eof() && ch != current_[-1]))
        return traits_type::eof();
    return traits_type::to_int_type(*--current_);
}
std::streamsize byte_array_buffer::showmanyc()
{
    assert(std::less_equal<const uint8_t *>()(current_, end_));
    return end_ - current_;
}

std::streampos byte_array_buffer::seekoff ( std::streamoff off, std::ios_base::seekdir way,
                                           std::ios_base::openmode which )
{
    if (way == std::ios_base::beg)
    {
        current_ = begin_ + off;
    }
    else if (way == std::ios_base::cur)
    {
        current_ += off;
    }
    else if (way == std::ios_base::end)
    {
        current_ = end_ + off;
    }
    if (current_ < begin_ || current_ > end_)
        return -1;

    return current_ - begin_;
}
std::streampos byte_array_buffer::seekpos ( std::streampos sp,
                                           std::ios_base::openmode which )
{
    current_ = begin_ + sp;
    if (current_ < begin_ || current_ > end_)
        return -1;
    return current_ - begin_;
}

支持tellg和seekg的可接受答案的扩展:

struct membuf : std::streambuf
{
    membuf(char* begin, char* end)
    {
        this->setg(begin, begin, end);
    }
    pos_type seekoff(off_type off, std::ios_base::seekdir dir, std::ios_base::openmode which = std::ios_base::in) override
    {
        if (dir == std::ios_base::cur)
            gbump(off);
        else if (dir == std::ios_base::end)
            setg(eback(), egptr() + off, egptr());
        else if (dir == std::ios_base::beg)
            setg(eback(), eback() + off, egptr());
        return gptr() - eback();
    }
    pos_type seekpos(pos_type sp, std::ios_base::openmode which) override
    {
        return seekoff(sp - pos_type(off_type(0)), std::ios_base::beg, which);
    }
};

这个类的用法保持不变

你试过std::istrstream吗?http://stdcxx.apache.org/doc/stdlibref/istrstream.html

从技术上讲,我认为它是不推荐的,但仍然是标准的一部分。

尝试Boost。Iostreams数组源类和接收类。

http://www.boost.org/doc/libs/1_47_0/libs/iostreams/doc/index.html