Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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

Background info: I'm going to be reading either a memory block or a large file line by line and processing those 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 the file stream version needs to be used, then the file won't fit into memory. Understandably, I could save the memory block to a file, and then access the same data with a file stream, but that seams like a waste of computer time.

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

like image 423
PSkocik Avatar asked Dec 11 '22 16:12

PSkocik


2 Answers

In C you may use sprintf and sscanf, in C++ there is the std::stringstream class that is constructed using a string. So you may make the function take an std::istream as argument and pass either std::ifstream of std::istringstream depending on the case.

like image 195
Ivaylo Strandjev Avatar answered Dec 24 '22 03:12

Ivaylo Strandjev


You could use the function open_memstream(3) and it's associated functions if it is available on your system. (glibc and POSIX 2008) : open_memstream(3) man page,

like image 20
iain Avatar answered Dec 24 '22 01:12

iain