Can unix commands be called from a C program?


Is it possible to call unix commands from a c program?
For example using "ls" to get a list of files in a directory and then store this to a file that could be searched within that program.

Thanks to anyone that can help me out with this,
I don't know about C (but I'm guessing yes), but you could always write a perl script to do stuff like that... but I only watch perl gods preform their magic; I only know a little perl myself.

Under Linux (i don't know for the rest of system Vs) it was


didn't try under OSX. Good luck

You can call a UNIX command from C using the 'system' function. However, the only thing the program you call can return to your program is a integer to indicate success or failure of the command.

To read in a command from UNIX, you can use the popen function to call a program & read its output.

But then, the most efficient way to do this in UNIX is to make some OS calls to read a directory. The functions opendir, readdir, and closedir will do what you want.

Of course, what kind of UNIX hack would I be if I didn't mention shell scripts. Many things that you want to do in UNIX can be handled via shell scripts. Writing a shell script using cut, sed, or awk is a great way to get things done.
You can run the unix system commands using the exec family of functions. For more help man the exec utility. I have given a sample program which runs banner(executable file) command from program. Program may require formating coz of HTML tags. I have not cared to remove them.

#include unistd.h
#include stdio.h

void main(int argc,char* argv[])
if(argc == 2)
printf(\\\"Usage: \\\\\\\\n\\\");
There are actually 3 major ways of executing a UNIX command from within a C program, namely exec(), system(), and popen().

The exec() family of system calls replaces the currently running process with the new process in question. This is usually used in conjunction with fork() to create a child process. For example:

if ( fork() == 0 ) {
execlp( "/usr/bin/ls", "/usr/bin/ls" );

Second, the system() call is very similar to performing a fork()/exec() and then waiting for the result. For example:

system( "/usr/bin/ls" );

Will perform a very same functionality as the previous example.

Third, if you wish send input or output to the command in question, you can use the "popen()" system call:

FILE *fp;

fp = popem( "/usr/bin/ls", "r" );

And at this point you can parse the output of the "ls" command.

I hope this helps.