c/c++语言开发共享如何获取此readdir代码示例以搜索其他目录

我目前正在使用一个代码示例,最初设计用于获取参数,然后在当前目录中搜索该参数,我试图通过替换“。”来搜索另一个目录(/ dev / shm to exact)。 “ 使用“/ dev / shm”但是当我搜索某些内容时代码没有任何内容*(请注意通配符)。 外卡搜索在当前目录中工作正常,所以我不认为这是外卡是问题,如果有人可以帮助我,虽然我真的很感激,谢谢!

#include  #include  #include  #include  static void lookup(const char *arg) { DIR *dirp; struct dirent *dp; if ((dirp = opendir(".")) == NULL) { perror("couldn't open '.'"); return; } do { errno = 0; if ((dp = readdir(dirp)) != NULL) { if (strcmp(dp->d_name, arg) != 0) continue; (void) printf("found %sn", arg); (void) closedir(dirp); return; } } while (dp != NULL); if (errno != 0) perror("error reading directory"); else (void) printf("failed to find %sn", arg); (void) closedir(dirp); return; } int main(int argc, char *argv[]) { int i; for (i = 1; i < argc; i++) lookup(argv[i]); return (0); } 

    opendir不处理通配符。 它需要一个真正的目录路径。 你说的时候我不确定你的意思

    通配符搜索在当前目录中有效

    如果你的意思是它在你的shell中工作,那是可以预料的。 shell将首先展开通配符,然后执行您键入的命令。

    那么如何解决这个问题呢? 在调用opendir之前使用glob自己扩展通配符。


    编辑:对不起,我以为你试图匹配目录名中的通配符。 看起来您希望使用通配符匹配目录内容。 在那种情况下,只需更换

     if (strcmp(dp->d_name, arg) != 0) 

     if (fnmatch(arg, dp->d_name, 0) != 0) 

    您也可以使用glob 。 它实际上会替换对opendir和循环的调用。 以下是使用glob的示例:

     #include  #include  static void lookup(const char *root, const char *arg) { size_t n; glob_t res; char **p; chdir(root); glob(arg, 0, 0, &res); n = res.gl_pathc; if (n < 1) { printf("failed to find %sn", arg); } else { for (p = res.gl_pathv; n; p++, n--) { printf("found %sn", *p); } } globfree(&res); } int main(int argc, char *argv[]) { int i; for (i = 2; i < argc; i++) lookup(argv[1], argv[i]); return (0); } 

    我不确定你在期待什么。 如果您的程序被称为lookup那么如果您在“当前目录”中调用它,那么该目录将文件保存为.s,something.2和something.3,如下所示:

     lookup something* 

    shell将它扩展为

     lookup something.1 something.2 something.3 

    并且您的程序将看到三个命令行参数,并且能够在readdir循环中找到匹配项。

    如果将opendir调用更改为“/ dev / shm”并从原始目录(具有某些内容的那个。[1-3])调用它,则shell将再次展开in the current directory的通配符。 但除非文件something.1,something.2和something.3也存在于/ dev / shm中,readdir循环将不会看到它们。

    请注意,您的查找function有点奇怪。 我希望它更像这样:

      static int lookup(const char * dir, const char *arg) { DIR *dirp; struct dirent *dp; if ((dirp = opendir(dir)) == NULL) { perror(dir); return -1; } while ((dp = readdir(dirp)) != NULL) { if (!strcmp(dp->d_name, arg)) { break; } } (void) closedir(dirp); printf("%s %sn", dp ? "found" : "failed to find", arg); return 0; } 

      以上就是c/c++开发分享如何获取此readdir代码示例以搜索其他目录相关内容,想了解更多C/C++开发(异常处理)及C/C++游戏开发关注计算机技术网(www.ctvol.com)!)。

      本文来自网络收集,不代表计算机技术网立场,如涉及侵权请联系管理员删除。

      ctvol管理联系方式QQ:251552304

      本文章地址:https://www.ctvol.com/c-cdevelopment/559841.html

      (0)
      上一篇 2021年1月27日
      下一篇 2021年1月27日

      精彩推荐