简体   繁体   中英

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?

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);
   }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM