Colin Simmons Colin Simmons - 1 month ago 16
C Question

Using a system call to execute "which" command in C

I'm trying to get the pathname for specific user input. For example, if the user inputs ls | wc I want to create two strings the first one being a which(ls), and the second one being a which(wc) so I have the pathname. I am doing this inside a C program and my code looks like the following.

/*This is a basic example of what i'm trying to do*/

char* temp;
printf("Enter a command\n");
/* assume user enters ls */
scanf("%s", temp);
char* path = system(which temp);
printf("Testing proper output: %s\n", path);

/*I should be seeing "/bin/ls" but the system call doesn't work properly*/


Can anyone point me in the right direction?

Answer

You are using an uninitialized pointer. But even if you had initialized it properly, it still wouldn't work because system() doesn't return the output of the command it executes. You want to use popen() to do that.

Here's an example (untested):

if (fgets(cmd, sizeof cmd, stdin)) {
   char cmd[512];
   cmd[strcspn(cmd, "\n")] = 0; // in case there's a trailing newline
   char which_cmd[1024];
   snprintf(which_cmd, sizeof which_cmd, "which %s", cmd);
   char out[1024];
   FILE *fp = popen(which_cmd);
   if (fp && fgets(out, sizeof out, fp)) {
      printf("output: %s\n", out);
   }
}