Search code examples
cexecls

Executing ls in a different directory in C using exec


Title is pretty self-explanatory on what I want to do.

My current try:

  chdir("/Path/I/want/");   //this is different that the path my program is located at
      char * ls_args[] = { "ls" , "ls -l", NULL};
      execv(ls_args[0], ls_args);
    }

I am not getting any errors or output, any help?


Solution

  • Execv function needs full path of the command which you have to execute. So, instead of giving "ls", you should find out where the ls is located in your system by

    $ which ls

    it will probably be in /bin folder. So you have to give "/bin/ls" to exec. Also any argument to ls should be another member in array. So instead of using

    char * ls_args[] = { "ls" , "ls -l", NULL};

    use

    char * ls_args[] = { "/bin/ls" , "-l", NULL};