0

So this program supposed to print all of the file information under a directory. Below is my c++ code:

    #include <iostream>
    #include <unistd.h>
    #include <cstdio>
    #include <sys/types.h>

    using namespace std;

    int main(int argc, char *argv[]){
        execvp("/bin/ls",&argv[0]);
fork(); // should I put it here?
        perror("failed to execute the command");
        cout<< "The PID is " << getpid() <<endl;    
        return 0;
    }

I think the command is supposed to be ls -a but how do I implement it in the program? Currently it only prints all of the files, not the information of each file.

Also how do I print the PID? Because the getpid() function doesn't seem to work.

Thank you!

elChino
  • 31
  • 1
  • 5
  • Related http://stackoverflow.com/questions/1723002/how-to-list-all-subdirectories-in-a-given-directory-in-c. – Pradhan Mar 16 '15 at 03:00

1 Answers1

0

To get a long listing of files, the command is ls -l. To include hidden files as well (those that start with a .), the command is ls -a. These of course can be combined into ls -la which will give a long listing of all files in the given directory.

Also, with the code you have, lines of code after the execvp call will never run. When you call an exec function, it replaces the current running program with whatever you are calling via exec. If you put the cout line before your call to execvp you should see the expected output. If you wanted to print those lines after calling execvp, you would need to use fork, which essentially creates a copy of your program as a child of the original program. This should give you some good resources about fork if that's the type of functionality you're hoping to achieve.

To properly call fork in C, your code will look something like this:

pid_t pid = fork();
if(pid == -1) //if there was an error
    ...
else if(pid > 0) //if child who resulted from the fork
    ...
else //if the parent who called the fork
    ...

I'm not exactly sure of your intention, so I'll let you fill in the code, but that's the general sense of using fork.

To pass arguments to your execvp call, you give it an array of strings which you are already doing in your code. You are passing all arguments to the execvp call, so after compiling, running ./a.out -la should pass -la giving you an exec call to ls -la.

Luke Mat
  • 147
  • 1
  • 2
  • 12
  • I added forking but was I doing it right? Also how do you execute the ls -a or ls -la command in C++? Thanks. – elChino Mar 16 '15 at 05:21
  • I've edited my answer to answer your questions. For a better sense of using `execvp` and giving arguments to it (like `-la`), check out this [page](http://pubs.opengroup.org/onlinepubs/009695399/functions/exec.html) for detailed information on using the `exec` family of functions. – Luke Mat Mar 16 '15 at 21:37