Access the memory block (/ C / C ++) as if it were a file stream

Is there a way to do this in C (or C ++)?

Background information: I am going to read either a memory block or a large file line by line, and process these lines one at a time, and I'm lazy to write the same thing twice, once for memory blocks and once for file streams. If you need to use the file stream version, the file will not fit into memory. It is clear that I could save the memory block to a file, and then access the same data with the file stream, but these are seams, like a waste of computer time.

I know about / dev / shm for Linux systems. Is there something more portable that gives me the same abstraction on a language layer (C or C ++)?

+4
source share
3 answers

In C you can use sprintf and sscanf , in C++ there is a class std :: stringstream , which is created using a string. Thus, you can force the function to accept std::istream as an argument and pass either std::ifstream from std::istringstream as the case may be.

+8
source

You can use the open_memstream (3) function and related functions, if available on your system. (glibc and POSIX 2008): open_memstream (3) man page,

+3
source

You can write your own stream buffer, for example:

 #include <streambuf> #include <istream> #include <iomanip> #include <iostream> template< class CharT, class Traits = std::char_traits<CharT> > class basic_MemoryBuffer : public std::basic_streambuf<CharT, Traits> { public: basic_MemoryBuffer(CharT* ptr, std::size_t size) { setg(ptr, ptr, ptr+size); } }; typedef basic_MemoryBuffer<char> MemoryBuffer; int main () { char data[] = "Hello, world\n42\n"; MemoryBuffer m(data, sizeof(data)-1); std::istream in(&m); std::string line; while(std::getline(in, line)) { std::cout << line << "\n"; } } 
+2
source

All Articles