If you do NOT need to use stdin
in your C++ program
This is the easy solution. Just pipe the output of the ls
command to your C++ program. Then, in your C++ program, read the contents of the file from stdin
like you would read from a normal file. Literally use stdin
wherever you need to provide a file descriptor. So, your command would look something like
ls ${PATH//:/ } | ./a.out
The |
denotes a pipe in bash. It takes stdout
from the first program (here ls
) and redirects it to stdin
of the second program (here your C++ program).
If you do need to use stdin
in your C++ program
This is going to be tricky. You essentially need to make your C++ program do everything itself. The first way to this that comes to mind is
- Read
$PATH
using getenv()
.
- Parse
$PATH
by replacing all occurrences of :
with
(a blank space). This is easy enough to do in a loop, but you could also use std::replace
.
- Now that you have the directory paths from
$PATH
, you simply need the contents of each directory. This post will help you get the contents of a directory.
UPDATE: Another Approach
I've thought of another way to approach your problem that allows you to use IO redirection (ie. use the pipe), and also use stdin
at the same time. The problem is that it is probably not portable.
The basic idea is that you read the output of ls
from stdin
(using the pipe operator in bash). Next, you essentially reset stdin
using freopen
. Something along the lines of
#include <stdio.h>
int main(void)
{
char buf[BUFSIZ];
puts("Reading from stdin...");
while(fgets(buf, sizeof(buf), stdin))
fputs(buf, stdout);
freopen("/dev/tty", "rw", stdin);
puts("Reading from stdin again...");
while(fgets(buf, sizeof(buf), stdin))
fputs(buf, stdout);
return 0;
}
The above code is from here. It reads stdin
, resets stdin
, and reads from stdin
again. I would suggest not using this approach for anything important, or for something that needs to work on several platforms. While it is more convenient since it allows you to use IO redirection while retaining the ability to use stdin
, it is not portable.