使用该系统在C程序中使用“RM”命令()stdlib.h中的功能 [英] using the 'rm' command in a c program using the system() function in stdlib.h
问题描述
我试图在主程序使用 RM
命令删除,我已经采取了命令行参数的文件。该值存储在的argv [2]
我已经尝试使用
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]"
文件名存储在的argv [2]
,因为我已经检查了。
有人请指导我!
推荐答案
为什么不使用 删除一> 或 取消链接 命令代替系统(RM ...)
?
删除(的argv [2]);
或取消链接(的argv [2]);
更新在系统(RM ...)
必须使用
如果你必须使用系统(RM ...)
,<一个href=\"http://stackoverflow.com/questions/2250140/using-the-rm-command-in-a-c-program-using-the-system-function-in-stdlib-h/2250150#2250150\">ZelluX在指出必须检索文件名的argv正确的[2]
。您可以检索的argv [2]
使用 字符串snprintf的 或 函数strncpy 。使用限制输入尺寸功能的变种是一个好主意因为有不保证字符串的长度的argv [2]
。
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]
.
根据您的应用程序,你可能还需要调用 统计 以请验证的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.
示例:
本示例调用 统计 以验证的argv [2]
是一个正常的文件和 asprintf 为缓冲区动态分配空间。
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);
}
}
这篇关于使用该系统在C程序中使用“RM”命令()stdlib.h中的功能的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!