1

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?

  • Yes, of course i did, and I tried slicing the command into different parameters, but it either gives no output or writes `stat` not found. – Balog Szilárd Oct 10 '19 at 06:36
  • I can't even run it using `system()` function. – Balog Szilárd Oct 10 '19 at 06:42
  • 1
    @churill please refrain from the comments or answers which advise people to "google it". Most of the time people come to these question/answer sites because a google search directed them here. – grovkin Oct 10 '19 at 06:45
  • 1
    @grovkin I find that is important to know. If I know that someone searched the docs and tried something before asking it is much easier to help him. Unfortunately many people ask questions without doing some research first. Now it is also clear what he tried. I did now mean to sound rude, sorry. – Lukas-T Oct 10 '19 at 07:01
  • 1
    @BalogSzilárd Thanks for showing what you already tried! Do you intend to insert the filename from `argv[1]` to where you have the parameter `"file"`? Maybe you can do `execl("/bin/stat", "stat", "-c", "\"%F %A %n\"", argv[1], NULL);`. – Lukas-T Oct 10 '19 at 07:03
  • Just executing `stat` like that is pretty pointless unless you're also capturing the output of the command... is that what you need help with? – Shawn Oct 10 '19 at 07:43
  • @churill Yeah, that's what I would like to achieve. But it doesn't give any output. – Balog Szilárd Oct 10 '19 at 09:34
  • @Shawn Yes, I thought it would be displayed in the terminal. – Balog Szilárd Oct 10 '19 at 09:36
  • Look into `popen()`. – Shawn Oct 10 '19 at 09:56
  • I found my problem. The `stat` command is located in `/usr/bin` instead of `/bin`. – Balog Szilárd Oct 10 '19 at 10:20
  • As @grovkin pointed out, most people come here in search of answers to their question. So please put your solution in an answer and mark it. It will be much easier to find. – the busybee Oct 10 '19 at 11:30

2 Answers2

2

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.

Goswin von Brederlow
  • 11,875
  • 2
  • 24
  • 42
0

I found my problem. The stat command is located in /usr/bin instead of /bin.