esrtr
esrtr

Reputation: 91

How to execute a command and read its output in C

I want to find path name with using which command like this:

system("which");

and then I use the output for a parameter for execv() function. How can I do that? Any suggestion?

Upvotes: 1

Views: 120

Answers (1)

P.P
P.P

Reputation: 121407

You are trying to solve it in the wrong way. which uses the PATH variable to locate the given executable. Using which to get the path and then passing it to execv() is needless because there's another variant of exec* which does the same: execvp().


To read the output of a command, you can use popen():

#include <limits.h>
#include <stdio.h>


char str[LINE_MAX];
FILE *fp = popen("which ls", "r");

if (fp == NULL) {
   /* error */
}

if(fgets(str, sizeof str, fp) == NULL) {
   /* error */
}

/*remove the trailing newline, if any */
char *p = strchr(str, '\n');
if (p) *p = 0; 

If your binary is in some buffer then you can use snprintf() to form the first argument to popen().

Upvotes: 3

Related Questions