Is it possible to read from named pipe (mkfifo) using c++ (stl)
using a stream - thus not defining in advance char *buffer[MAX_SIZE]
for the read operation?
I want to read till the buffer ends and put the result into std::string
.
(Current method: bytes = read(fd, buffer, sizeof(buffer));
requires allocation some kind of buffer in advance.)
There's nothing magical about piping to your program it just turns your
cin
reading from the stream instead of the user's input from the console: Linux terminal pipe to my C++ programA simple glance at this question's edit history will show that this question has greatly improved from it's original version thanks to Konrad Rudolph (the other answerer on this question.) In a move of further dastardliness I'm going to scrape 2 of his solutions for slurping a stream into
string
:istreambuf_iterator
method:stringbuf
copy method:You can read about the pros and cons of each on their respective posts. To use this code, say that your compiled program is named
main
you would pipe to it like this:Named pipes created with
mkfifo
behave like regular files. Thus they can be accessed usingstd::ifstream
andstd::ofstream
:Run:
And elsewhere:
… this will cause
./main
to print “Hello world!” to the standard output.