Home >Backend Development >C++ >How to Create an Input Stream from Read-Only Memory in C ?

How to Create an Input Stream from Read-Only Memory in C ?

Susan Sarandon
Susan SarandonOriginal
2024-11-09 20:45:02623browse

How to Create an Input Stream from Read-Only Memory in C  ?

Creating an Input Stream from Read-Only Memory

You have a data buffer pointed to by a const char* pointer containing an ASCII string. You want to read the data as if it were a stream, without copying or altering it.

Solution

To achieve this, you can create a custom stream buffer. Here's how:

#include <streambuf>
#include <istream>

struct membuf: std::streambuf {
    membuf(char const* base, size_t size) {
        char* p(const_cast<char*>(base));
        this->setg(p, p, p + size);
    }
};

struct imemstream: virtual membuf, std::istream {
    imemstream(char const* base, size_t size)
        : membuf(base, size),
          std::istream(static_cast<std::streambuf*>(this))
    {}
};

The membuf class contains the stream buffer that reads from the const char* pointer. The imemstream class inherits from membuf and adds the necessary functionality to make it an input stream.

To use imemstream, you can instantiate it and use it like this:

imemstream in(data, size);
in >> value;

This will read the data from the buffer as if it were a stream, without modifying it.

The above is the detailed content of How to Create an Input Stream from Read-Only Memory in C ?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn