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?
You must use
sh
shell syntax, you are not doing this.I think I would just add the shell to the system command:
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:
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: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:
or possibly:
or:
or similar.
But it's probably better to use JeremyP's answer.