I want to manipulate the output of the ls -al command in my C program. Is there a way to do it ?
int main()
{
int return_value;
return_value = system("ls -al ");
return return_value;
}
I want to manipulate the output of the ls -al command in my C program. Is there a way to do it ?
int main()
{
int return_value;
return_value = system("ls -al ");
return return_value;
}
You need a pipe to the process.
#include <stdio.h>
#include <stdlib.h>
int main()
{
FILE *fp;
char output[1024];
fp = popen("/bin/ls -al", "r");
if (fp == NULL)
exit(1);
while (fgets(output, 1023, fp) != NULL)
printf("%s", output);
pclose(fp);
return 0;
}
You could use popen(3) on /bin/ls
as answered by Baris Demiray.
But in your particular case (getting the files in a directory), you don't really need to start some external process running ls
, you could simply use opendir(3) & readdir(3) to read the directory entries, and use stat(2) on each of them (you'll build the path using snprintf(3)). See also glob(7), nftw(3) and read Advanced Linux Programming
Notice that the system(3) is a very poorly named standard C library function. It is not a direct system call (they are listed in syscalls(2)...), but uses fork(2), execve(2), waitpid(2), etc...