i am trying to use the rm command in the main routine for deleting a file that i have taken a command line argument. The value is stored in argv[2] i have tried using
system("rm argv[2]");
system("rm ./argv[2]");
system("rm $HOME/argv[2]");
But it gives me an error saying
"cannot locate file argv[2]"
The filename is stored in argv[2] as I have checked it.
Someone please guide me!
Why not use the remove or unlink command instead of
system("rm ...")?remove(argv[2]);orunlink(argv[2]);Update in the case that
system("rm ...")must be usedIf you must use
system("rm ..."), ZelluX is correct in stating that you must retrieve the filename fromargv[2]. You can retrieve the string inargv[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 inargv[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.