PDA

View Full Version : Shell commands in other programming languages



rharriso
August 20th, 2007, 08:23 AM
I feel like I should know this, but its never come up.

Is it possible to take advantage of the shell commands in languages such as C++ and Java? If so how?

Wybiral
August 20th, 2007, 09:13 AM
I feel like I should know this, but its never come up.

Is it possible to take advantage of the shell commands in languages such as C++ and Java? If so how?

Define "take advantage".

I assume by shell commands you mean "system"?

Ramses de Norre
August 20th, 2007, 03:54 PM
Java: Runtime.getRuntime().exec(command);

C: system(command);

In Java to catch the output you've got a little more work:

InputStream is=Runtime.getRuntime().exec("ls /").getInputStream();
Scanner scan=new Scanner(is);
String out="";
while(scan.hasNext())
{
out+=scan.nextLine()+"\n";
}

In C you can do this by using popen(), but I don't know exactly how to do so.

pmasiar
August 20th, 2007, 04:31 PM
Define "take advantage".

IMHO OP wanted to use OS/shell commands.

This home turf of so called "scripting" languages, like Perl and Python.

rharriso
August 20th, 2007, 06:18 PM
Exactly, I know how to do that in Pearl, but I much prefer C++ and Java.
I wanted to know how to, I'm going to say output, shell commands from a C++ script.

Mr.Carramba
August 20th, 2007, 06:21 PM
Java: [snip]
In C you can do this by using popen(), but I don't know exactly how to do so.

it's actualy not pure c.. it's POSIX (thread programing), in
u start new thread were you "save" input or directly pass it to another thread or your maine program

rharriso
August 20th, 2007, 06:38 PM
I tried simply using the system() function in C++. Thats worked with a couple of the commands. Has anyone run into trouble with that method?

Mr.Carramba
August 20th, 2007, 06:54 PM
it is depend what you want to do...
since system() return value is allmost useless for controlling exit status of started aplication