Ubuntu

如何在沒有系統或bash(在c中)的execv中使用萬用字元?

  • April 15, 2021

我想用

char *argv[] = {"rm", "-r", "/home/banana/Quest/*/", NULL};
execv("/bin/rm", argv);

在 C 文件中刪除 Quest 文件夾中的所有目錄。但是萬用字元不起作用。如果沒有系統或 bash,我怎麼能做到這一點?我聽說過 glob,但它有點令人困惑。

我嘗試了類似的東西:

glob_t globbuf;
int err = glob("/home/solxius/modul2/petshop/*/", 0, NULL, &globbuf);
globbuf.gl_pathv[0] = "rm";
globbuf.gl_pathv[1] = "-r";
char *argv[] = {"rm", "/home/solxius/modul2/petshop/", NULL};
execvp("bin/rm", &globbuf.gl_pathv[0]);

但它不起作用

嗯,glob()使用起來似乎很簡單。當然,您可以使案例如readdir()和手動完成fnmatch()

#include <glob.h>
#include <stdio.h>

/* run as 'globtest "*.txt"' */

int main(int argc, char *argv[])
{
   glob_t g;
   if (argc < 2) {
       printf("usage: %s <pattern>\n", argv[0]);
       return 1;
   }
   int ret = glob(argv[1], 0, NULL, &g);
   if (ret == 0) {
       printf("found %d matches:\n", (int) g.gl_pathc);
       for (int i = 0; g.gl_pathv[i]; i++) {
           printf("  %s\n", g.gl_pathv[i]); 
       }
   } else if (ret == GLOB_NOMATCH) {
       printf("no matches!\n");
   } else {
       printf("some error happened\n");
   }
}

當然,您仍然需要將(指向的)字元串複製到傳遞給execv()/的數組中execve()

引用自:https://unix.stackexchange.com/questions/645238