How do i invoke the ls command within a C code
Hey everyone!!
What i'm just trying to do is to invoke the ls command, like when we use: getpid() ..the output shows the PID number. Now i'd like to do the same thing but instead of using getpid() use something to execute the ls command (current directory) and ls / command ( root directory) Incomplete code: #include <stdio.h> int main() { char x[100]; //char list [1000]; -> ls stuff? i think this is wrong while(1) { printf("Command: "); fgets( x, 100, stdin); if(strcmp(x, "pids\n") == 0 ) printf("My pid is %d and the ppid is %d, \n" , getpid(), getppid()); //now i'd like to do the same thing but for ls and // ls / else if(strcmp(x, "lists\n") == 0) printf( /*execute ls command*/); else if (strcmp(x, "root\n") == 0) printf( /*execute ls / command( root directory)*/); } return 0; } any suggestion? Thks [[]] |
What you want is to use a system call.
the GNU GCC docs describe how, but state there are functions to do almost everything in gcc already. |
doesn't say what i wanna know :S
getls() , does not exists lol what should i use? by the way how do i get out of the while loop? Like in java we use: System.exit(0); in C what do we use? Thk you so much! |
Code:
FILE *fp=popen("ls -l", "r"); |
Quote:
the system call when finished returns control to the calling program, return is the end of function signal, 0 is the standard no error indicator. |
ls.c source code
I thought I'd add this just in case: Download the source code for the ls command and study how it is implemented. It is in the "coreutils" package provided by the GNU software group.
http://ftp.gnu.org/pub/gnu/coreutils/ -- Tony |
ok thks.
Last question how do we get out of a while loop? if i use: exit(0); it gives me error ! :S so what do we use in C code? |
Hi, John -
I was about to suggest "man popen", when I got sidetracked ... and you got about six other replies. For whatever it's worth, here's a code sample that illustrates "popen": Code:
#include <stdio.h> Quote:
|
Reading the contents of a directory is similar to reading the contents of a file. A directory is a special file containing a list of inode number / name pairs.
Look through the <sys/types.h> and <dirent.h> headers. From There is an opaque type named DIR that is similar to the FILE type. Excerpt from Linux Programming by Example by Arnold Robbins: Code:
int Your example System.exit(0); is for improperly bailing out of a program if used in a while loop. The touch pad on my laptop is a bit touchy today. The code got rearranged a few times while typing. I hope it is correct now. |
All times are GMT -5. The time now is 11:27 AM. |