Linux system call output in C program

I want to manipulate the output of the ls -al command in my C program. Is there a way to do this?

int main() { int return_value; return_value = system("ls -al "); return return_value; } 
0
source share
2 answers

You need a channel for 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; } 
+2
source

You can use popen (3) in /bin/ls as answered by Baris Demirai.

But in your specific case (getting files in a directory) you really don't need to start some external process with ls , you can just use opendir (3) and readdir (3) to read entries in the directory and use stat (2) for each of them (you build the path using snprintf (3) ). See Also glob (7) , nftw (3) and read Linux Advanced Programming

Note that system (3) is a very poorly named C standard library . This is not a direct system call (they are listed in syscalls (2) ...), but it uses fork (2) , execve (2) , waitpid (2) , etc.

+1
source

All Articles