0

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;
}
NB2345
  • 71
  • 1
  • 1
  • 6
  • 2
    possible duplicate of [How can I run an external program from C and parse its output?](http://stackoverflow.com/questions/43116/how-can-i-run-an-external-program-from-c-and-parse-its-output) – Michael Jul 28 '15 at 08:25

2 Answers2

2

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;
}
Baris Demiray
  • 1,539
  • 24
  • 35
1

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...

Community
  • 1
  • 1
Basile Starynkevitch
  • 223,805
  • 18
  • 296
  • 547