Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get the full stream output with pstreams?

http://pstreams.sourceforge.net/ pstreams is an apparently very simple library, re-implementing popen() for C++.

The library is very simple to install, consisting of only one single header file. You can download the header file here and add it to your application:
http://pstreams.cvs.sourceforge.net/viewvc/pstreams/pstreams/pstream.h?view=log

I thought what I wanted was pretty straightforward: send a command to the system and get its output. The home page of pstreams (above) and the documentation offer the following example:

redi::ipstream in("ls ./*.h");
std::string str;
while (in >> str) {
    std::cout << str << std::endl;
}

It seems to work well, but the code actually strips all spaces and carriage return from the output. Try this:

redi::ipstream in("ls -l"); /* The command has a slightly more complicated output. */
std::string str;
while (in >> str) {
    std::cout << str
}
std::cout << std::endl;

and we get a looong concatenated string without any space.

I did my best to understand the documentation, and the closest I have come to a solution is this:

 redi::ipstream in("ls -l");
 std::string str;
 while (!in.rdbuf()->exited()) {
 in >> str;
 }
 std::cout << str << std::endl;

However, the output is completely truncated at the first space.

I am stymied.

Related questions:
popen equivalent in c++
How to execute a command and get output of command within C++ using POSIX?

Note to moderators: a pstreams tag is required for this question and the other two above.

like image 469
augustin Avatar asked Dec 14 '25 12:12

augustin


1 Answers

The streaming operator >> is designed to read a word at a time to a std::string, while skipping surrounding whitespace, just as you do when reading a number.

If you want to read an entire line of text at a time, use getline instead.

std::getline(in, str);
like image 192
Bo Persson Avatar answered Dec 17 '25 03:12

Bo Persson