Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get an istream from a char*

Tags:

c++

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.

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.

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

like image 960
Damian Avatar asked Oct 16 '11 02:10

Damian


People also ask

Is get () C++?

C++ gets()The gets() function in C++ reads characters from stdin and stores them until a newline character is found or end of file occurs.

How do I read one character from a file in C++?

If you prefer to read one character at a time (including whitespace characters), you can use the get operation: char ch; while (inFile. get(c)) { ... } In this example, each time the while loop condition is evaluated, the next character in the input file is read into variable ch.

How do I read istream?

Other ways to read a std::istreamTo read a line of input, try the getline() function. For this, you need #include <string> in addition to #include <iostream> . To read a single char: use the get() method. To read a large block of characters, either use get() with a char[] as the argument, or use read() .

How do I use istream in C++?

2.2 File InputConstruct an istream object. Connect it to a file (i.e., file open) and set the mode of file operation. Perform output operation via extraction << operator or read() , get() , getline() functions. Disconnect (close the file) and free the istream object.


1 Answers

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

Which outputs:

line: I'm a buffer with embedded nullsand line line:  feeds 
like image 188
HostileFork says dont trust SE Avatar answered Sep 21 '22 06:09

HostileFork says dont trust SE