Why not use the remove or unlink command instead of system("rm ...")
?
remove(argv[2]);
or unlink(argv[2]);
Update in the case that system("rm ...")
must be used
If you must use system("rm ...")
, ZelluX is correct in stating that you must retrieve the filename from argv[2]
. You can retrieve the string in argv[2]
using snprintf or strncpy. Using the variants of the functions that restrict the input size is a good idea as there is no guarantee as to the length of the string in argv[2]
.
Depending on your application, you may also want to call stat to verify that the string in argv[2]
is indeed a file and possibly restrict the type of file.
Example:
This example calls stat to verify that argv[2]
is a regular file and asprintf to dynamically allocate space for the buffer.
char *p;
struct stat st;
if (stat(argv[2], &st) == 0 && S_ISREG(st->st_mode))
{
if (asprintf(&p, "rm %s", argv[2]) != -1)
{
system(p);
free(p);
}
}