0
我试图从当前工作目录中删除文件。当我尝试使文件未找到时打印“无效文件”时,它会引发分段错误。这段代码是更大程序的一部分。从当前目录中删除文件
代码:
printf("\nEnter your current password:\t");
scanf("%s",temp2);
comp2 = strcmp(password,temp2);
file = (char*)malloc(100 * sizeof(char));
if(comp2 == 0)
{
int value;
printf("\nEnter the file name:\t");
scanf("%s",file);
sprintf(cmd,"rm -i %s",file);
value=system(cmd);
if(value == -1)
printf("\nFile not Found. Exiting Program");
}
else
printf("\nThe password is incorrect. Please try again.");
break;
任何帮助吗?提前致谢。
“cmd”在哪里分配?另外,'rm -i'是一个交互命令,但你不是一个交互过程。另外,C有一个'unlink'调用,所以你不必使用'system' ... – Joe
如何使用[remove](http://pubs.opengroup.org/onlinepubs/009695299/functions/remove.html )([注意事项](https://www.securecoding.cert.org/confluence/display/seccode/FIO08-C.+Take+care+when+calling+remove%28%29+on+an+open+file ))或[取消链接](http://pubs.opengroup.org/onlinepubs/009695299/functions/unlink.html)? – miku
在子程序中执行'rm'不是从C程序中删除文件的好方法。它对各种潜在的问题都是开放的,比如不寻常的'$ PATH'导致'rm'不被发现,或者文件名中的空格导致'rm'误解你想要删除的文件。使用系统调用,例如'unlink',让你自己的*程序删除文件,而不是运行某个* other *程序来删除它。 – Wyzard