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 }
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?
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);
}
}
Warning: all error handling omitted, not compiled and tested, readdir might return .
and ..
which also need to be not deleted.
You will probably need to use this:
system("/bin/bash -c 'rm !(svn)'")
or possibly:
system("/bin/bash -O extglob -c 'rm !(svn)'")
or:
system("find . -maxdepth 1 ! -name 'svn' -delete")
or similar.
But it's probably better to use JeremyP's answer.
You must use sh
shell syntax, you are not doing this.
I think I would just add the shell to the system command:
system("/bin/csh rm !(svn)");
or whatever shell you use.
Workaround: Move file outside directory (f. e. in /tmp or ..), delete all, move it back (do it using several system() calls).
Another approach:
find . -prune ! -name svn | xargs /bin/rm -f
精彩评论