Executing system(" ") command with a string variable inside

  • Follow


I need to run system(" ") command in C program of Linux system. But
the command inside is not simply a literal string. It's including a
string variable inside the command. I need the string variable to be
expressed first, and then run the command. How to do this? Thanks.
0
Reply chen_zhitao (70) 6/13/2009 9:57:44 AM

>I need to run system(" ") command in C program of Linux system. But
>the command inside is not simply a literal string. It's including a

So declare a character array that's big enough, or malloc() one, and
put the string in it.  Then call system(stringbuffer).  system() has
no requirement that its argument be a string literal.

>string variable inside the command. I need the string variable to be
>expressed first, and then run the command. How to do this? Thanks.

sprintf() (or snprintf()) is often useful for this.  You can also
build the string with lots of other methods, such as combinations
of strcpy() and strcat().

0
Reply gordonb.q37o8 (1) 6/13/2009 10:11:13 AM


Kuhl wrote:

> I need to run system(" ") command in C program of Linux system. But
> the command inside is not simply a literal string. It's including a
> string variable inside the command. I need the string variable to be
> expressed first, and then run the command. How to do this? Thanks.

char cmd[1024];
const char *path = "/etc";
sprintf(cmd, "ls -l %s", path);
system(cmd);

-- 
printf -v email $(echo \ 155 141 162 143 145 154 155 141 162 \
143 145 154 100 157 156 154 151 156 145 56 156 154 | tr \  \\)
#   O Herr, lass Hirn vom Himmel fallen!   #
0
Reply we-love-all-spam (43) 6/13/2009 11:34:38 PM

Marcel Bruinsma a �crit :
> char cmd[1024];
> const char *path = "/etc";
> sprintf(cmd, "ls -l %s", path);
> system(cmd);

A safer version is probably better:

char cmd[1024];
const char *path = "/etc";
if (snprintf(cmd, sizeof(cmd), "ls -l %s", path) >= sizeof(cmd)) {
   error(EXIT_FAILURE, 0, "format error");
}
system(cmd);


0
Reply xroche (185) 6/14/2009 8:19:52 AM

3 Replies
66 Views

(page loaded in 0.109 seconds)

Similiar Articles:













7/22/2012 1:13:09 AM


Reply: