Created
May 28, 2016 01:11
-
-
Save mlfarrell/28ea0e7b10756042956b579781ac0dd8 to your computer and use it in GitHub Desktop.
C++ streams from memory buffer
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
struct membuf : std::streambuf | |
{ | |
membuf(char *begin, char *end) : begin(begin), end(end) | |
{ | |
this->setg(begin, begin, end); | |
} | |
virtual 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(begin, end+off, end); | |
else if(dir == std::ios_base::beg) | |
setg(begin, begin+off, end); | |
return gptr() - eback(); | |
} | |
virtual pos_type seekpos(streampos pos, std::ios_base::openmode mode) override | |
{ | |
return seekoff(pos - pos_type(off_type(0)), std::ios_base::beg, mode); | |
} | |
char *begin, *end; | |
}; | |
static istream *currentReadStream; | |
/* from memory.. */ | |
membuf sbuf(buf, buf+dataSz); | |
std::istream in(&sbuf); | |
currentReadStream = ∈ | |
/* or from file */ | |
std::ifstream file(filename, ios::binary); | |
currentReadStream = &file; | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment