user2527401
user2527401

Reputation: 9

Passing C variable in Shell command

I am stuck at a problem. I want to use C variable in a shell command (dd).

Suppose abc.c is my C program.

int main()
 {
    int block = 1313; /*any integer */
    system("dd if=device of=output-file bs=4096 count=1 skip=$((block))");
    return 0;
 }

Now, if I use 1313 in place of block in the dd command then it works fine. But when I write block then it writes zeros in output-file as block is a C program variable and is used in the shell command.

Upvotes: 0

Views: 181

Answers (1)

mattn
mattn

Reputation: 7723

Use snprintf().

char buf[256];
const int block = 1313;
snprintf(buf, sizeof buf,
         "dd if=device of=output-file bs=4096 count=1 skip=%d", block);
system(buf);

Upvotes: 6

Related Questions