C 系统函数导致错误 'sh: Syntax error: "(" unexpected ' [英] C system function causes error 'sh: Syntax error: "(" unexpected '
问题描述
我在 Linux 上用 C 语言编写了一个简单的程序来删除目录中除了名为 svn
的所有文件,如下所示:
I wrote a simple program in C on Linux to delete all the files in a directory except one called svn
like this:
1 #include <stdio.h>
2
3 int main()
4 {
5 system("rm !(svn)");
6 return 0;
7 }
但是当我编译并运行它时,终端说:sh: Syntax error: "(" unexpected
But when I compile and run it, the terminal says: sh: Syntax error: "(" unexpected
但是,当我直接在终端中键入并运行命令时,一切都正确完成.有什么想法吗?
However, when I type and run the command in the terminal directly, all things are done correctly. Any ideas?
推荐答案
答案是不要使用 system
.使用 Linux 系统调用列出目录中的文件并使用 unlink() 删除它们.类似的东西:
The answer is don't use system
. Use the Linux system calls to list the files in the directory and remove them using unlink(). Something like:
DIR* dirHandle = opendir(dirName);
struct dirent* dirEntry;
while ((dirEntry = readdir(dirHandle)) != NULL)
{
if (strcmp(dirEntry->d_name, "svn") != 0)
{
unlink(dirEntry->d_name);
}
}
警告:省略所有错误处理,未编译和测试,readdir 可能返回 .
和 ..
也不需要删除.
Warning: all error handling omitted, not compiled and tested, readdir might return .
and ..
which also need to be not deleted.
这篇关于C 系统函数导致错误 'sh: Syntax error: "(" unexpected '的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!