从char *获取istream [英] Get an istream from a char*

查看:1528
本文介绍了从char *获取istream的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have a char* and the data length that I'm receiving from a library, and I need to pass the data to a function that takes an istream.

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

I know I can create a stringstream but that will copy all the data. And also, the data will surely have 0s since it's a zip file, and creating a stringstream will take the data until the first 0 I think.

有任何方法从一个char *中创建一个istream,它的大小不能复制所有的数据?

Is there any way to create an istream from a char* and it's size without copying all the data?

推荐答案

=http://bytes.com/topic/c/answers/582365-making-istream-char-array>在网络上找到,您是否获得自己的 std :: streambuf 类,但很容易,似乎工作:

Here's a non-deprecated method found on the web, has you derive your own std::streambuf class, but easy and seems to work:

#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;
}

哪些输出:

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

这篇关于从char *获取istream的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆