Question:
Command line calls in C program?
anonymous
2007-11-12 13:26:59 UTC
I would like to write a simple C program that basically calls the /usr/bin/ls -l command, but I am not sure exactly how to do this. I know popen and pclose are available, but I do not know how to use these. Would anyone be able to help? Some example code of how I could do this would be the most helpful. Thanks.
Four answers:
David W
2007-11-12 20:20:15 UTC
The two earlier answers are OK, as far as they go.



Yes, if you just want to run the command and don't care about the output, just use system().



You can execute a command directly using one of the exec functions (execl(), execv(), etc.), but you need to deal with a lot of stuff yourself (like forking a child process), so that's probably not what you want.



You mentioned popen(). You can use popen() if you want to be able to read the stdout of the program you run. So, for example, if you do:



f = popen("ls -l", "r");



while (!eof(f)) {

count = fread (buffer, sizeof buffer, 1, f);

// process output of ls

}

pclose(f);



you'll be able to read the data written by the command.



Similarly, if you want to run a command and write data to its stdin, you can use popen("...command...", "w"). popen(...,"r+") will let you read *and* write to the command.



And remember, always use pclose() to close a stream created by popen(). Don't use fclose(). fclose() won't clean up everything.



Hope this helps.
photog_35
2007-11-12 13:40:03 UTC
The question is: Do you need the output from the 'ls' command to ba available to your 'C' program too, or just to come to the screen?



If you want it to just come to the screen, use the 'system' function call: system("ls -l");



If you need the output, you can direct it to your stndard output which can be read by your standard in.



Or use the execl command. That way you have more control as to where the outputs go.



But if you just want the information locally for your program, use the following functions:



opendir()

readdir();

stat();



to open a directory, read each entry, and get the file information. This way you can format the output any way you want to, including other information that 'ls' may not provide.
saulsbery
2016-10-02 09:21:03 UTC
//run your software from a command line on the spot, and make contact with with quite some arguments // programName cat dogs hampster zebra double whiskey int substantial(int numberOfInputs, char* argv[]) { //numberOfInputs is the style of command line //arguments inclusive of the call of your software printf("software is %sn", argv[0]); for(int i=a million;i
Runa
2007-11-12 13:35:04 UTC
#include



int main(void)

{

system("ls -l");

return 0;

}


This content was originally posted on Y! Answers, a Q&A website that shut down in 2021.
Loading...