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?
Advertisement
Answer
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.