What I need to do?
I need to read the file from RAM
How I am doing it?
I use std::istream
, because it know how to read from buffer. So, there is method that know how to read file size(according to this SO answer https://stackoverflow.com/a/6039648/5709159)
long getFileSize(const std::string &filename)
{
struct stat stat_buf{};
int rc = stat(filename.c_str(), &stat_buf);
return rc == 0 ? stat_buf.st_size : -1;
}
Then I use membuf to copy bytes from file to buffer (according to this SO answer https://stackoverflow.com/a/13586356/5709159)
struct membuf : std::streambuf
{
membuf(char *base, std::ptrdiff_t n)
{
this->setg(base, base, base + n);
}
};
Full implementation looks like this
long size = getFileSize(filename);
membuf sbuf(0, size);
std::istream file(&sbuf);
But, I am now sure that sbuf(0, size);
that 0
here is on the right place...
So, question is - how to set membuf
with right size ?