C system function causes error 'sh: Syntax err

2019-08-21 14:38发布

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?

5条回答
别忘想泡老子
2楼-- · 2019-08-21 14:51

You must use sh shell syntax, you are not doing this.

查看更多
狗以群分
3楼-- · 2019-08-21 14:58

I think I would just add the shell to the system command:

system("/bin/csh rm !(svn)");

or whatever shell you use.

查看更多
在下西门庆
4楼-- · 2019-08-21 15:06

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
查看更多
老娘就宠你
5楼-- · 2019-08-21 15:07

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.

查看更多
该账号已被封号
6楼-- · 2019-08-21 15:12

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.

查看更多
登录 后发表回答