从char获取一个istream*

Dam*_*ian 51 c++ istream

我有一个char*和我从库中收到的数据长度,我需要将数据传递给一个带有istream的函数.

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

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

Hos*_*ork 65

这是在网上找到的一种不推荐使用的方法,你是否派生了自己的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 nulls\0and line\n 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;
}
Run Code Online (Sandbox Code Playgroud)

哪个输出:

line: I'm a buffer with embedded nullsand line
line:  feeds
Run Code Online (Sandbox Code Playgroud)

  • 有人在没有评论的情况下对此进行了投票.所以它可能有问题.但在有人说出来之前,我们永远都不知道是什么. (5认同)
  • 有一篇很棒的博客文章[这里](http://www.mr-edd.co.uk/blog/beginners_guide_streambuf)(见例2)详细解释了这一点. (3认同)
  • 尼斯,简单的解决方案(我不是拒绝投票的人)。但是要注意,除非在streambuf中实现`seekoff`和`seekpos`,否则iostream上的`tellg`和`seekg`将不起作用。您可能也可能不想提供`setbuf`。 (2认同)

Zun*_*Tzu 12

使用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);
Run Code Online (Sandbox Code Playgroud)

甚至更简单:

#include <boost/interprocess/streams/bufferstream.hpp>
using namespace boost::interprocess;

bufferstream input_stream(my_ptr_to_char, byte_count);
Run Code Online (Sandbox Code Playgroud)


cat*_*lan 7

我需要一个支持tellg并且seekg不需要提升的解决方案.

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_;
};
Run Code Online (Sandbox Code Playgroud)

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_;
}
Run Code Online (Sandbox Code Playgroud)


Nem*_*emo 6

唯一(简单)便携方式包括制作副本:

std::istringstream ss(std::string(buf,len));
Run Code Online (Sandbox Code Playgroud)

实际上,这很可能会复制数据两次,一次创建string和一次创建istringstream.(也许C++ 11可以通过移动构造函数避免其中一个副本;我不确定.)

但是,如果你很幸运,你的C++实现将允许你这样做:

std::istringstream ss;
ss.rdbuf()->pubsetbuf(buf,len);
Run Code Online (Sandbox Code Playgroud)

在GNU C++(我相信,其他一些实现)下,这将创建字符串流而不复制数据.但这是根据规范的"实现定义"行为.(另见这个问题.)

通过包含len参数,可以确保这两个参数都没有问题.

执行所需操作的唯一可移植方法是实现自己的子类stringbuf并使用它来初始化stringstream.不适合胆小的人.


小智 5

支持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);
    }
};
Run Code Online (Sandbox Code Playgroud)

该类的用法保持不变。