-2

could anyone provide a small example or direct me to proper reading material in order to solve the following problem:

    ls | ./myprog

What I would like to achieve is that my program reads information from ls and just print it on the screen.

I need c++ example, and if possible to do this through boost lib

thnx

P.S.

Thank you all it worked

user8060
  • 53
  • 1
  • 2
  • 8
  • Shouldn't need anything particularly special - just regular `while(std::cin >> myvariable) { ... }` or similar should work. The beauty of the "generic input system" is that pipes, redirected files and consoles work the same way. – Mats Petersson Mar 08 '15 at 16:38
  • The "pipe" is not part of your program but rather how the environment for running your program is set up by the shell. – Ulrich Eckhardt Mar 08 '15 at 16:52

2 Answers2

0

In C, all you need to do is read the file descriptor 0:

read(0, …, …);

In C++, you can do this by using std::cin:

#include <iostream>
int main() {
    std::cin >> /* a variable you want to direct the input to */
    return 0;
}

That's standard C++ that is fully compatible with boost. For the way to use it, I leave it to you to read more on the manual and the plethora of examples you can find online.


for opening a file or reading from stdin you can do something in the following fashion:

shared_ptr<istream> input;
if (filename == "-" || filename == "")
    input.reset(&cin, [](...){});
else
    input.reset(new ifstream(filename.c_str()));

// ...

(answer copied from https://stackoverflow.com/a/2159469/1290438)

Basically, if you don't give a filename parameter, you consider data comes from stdin. That's the way cat works.

Community
  • 1
  • 1
zmo
  • 24,463
  • 4
  • 54
  • 90
  • thnx ! what would then be a solution if sometimes i want to read from file and sometimes from stdin. let say I only have one loop and I need to read input character one at a time (get()) i cannot use cin then. Right? – user8060 Mar 08 '15 at 17:33
  • Of course you read one character at a time, just you the [`read()` method](http://www.cplusplus.com/istream::read) of `istream` which is the class of `cin`, to which you can give the number of character to read. But do you really want to that? If you're reading a file as input, you might prefer to read it line by line. – zmo Mar 08 '15 at 21:55
0

this code matches exactly your Problem:

#include <iostream>

using namespace std;

    int main()
{ 
while (true)
    {
        string x;
        cin >> x;
        cout << x << endl;
    }
}

you have to put this code into your "myprog" cpp file and then type the command you've mentioned. It simply puts the input from the ls program to your screen