Search code examples
c++clinuxexecexecl

How can I run system commands in C/C++ using `execl()`, passing the function arguments only as a command line, not as an executable file?


I would like to execute this command in a C/C++ program: stat -c "%F %A %n" *filename goes here* The filename is stored in the main function's argv[1].

I tried it as execl("/bin/stat", "stat", "-c", "\"%F %A %n\"", "file", NULL);

How should the execl() command look like to achieve the result?


Solution

  • Your command should look like this:

    int res = execl("/bin/stat", "stat", "-c", "\"%F %A %n\"", argv[1], NULL);
    if (res == -1) {
       perror("/bin/stat");
       exit(1);
    }
    

    Then the perror would show you:

    /bin/stat: No such file or directory
    

    and you would realize that stat is in /usr/bin or that using execlp would have been a good idea.