How to add to *argv for execv?

Viewed 124

Let's say I want to remove something with execv, but I don't know what to remove yet.

char *argv[] = {"rm", "-r"};

Now, I do! How do I add to the argv? How to end it with a NULL? Thanks!

1 Answers

If you want to insert a single file name, a fixed number of file names or a defined maximum number of file names, you could statically define and initialize the pointer array with NULL pointers as placeholders

/* placeholder for two file names and terminating NULL pointer */
char *argv[] = {"rm", "-r", NULL, NULL, NULL};

and replace the NULL pointer(s) at index 2 (and 3) with one or two file names later

char filename1[1024];
char filename2[1024];

/* input or construct filenames as strings somehow */

argv[2] = filename1;
argv[3] = filename2;

If you need to handle an unknown number of file names you might have to dynamically allocate a pointer array of the required size.

Related