c - 我如何获得此readdir代码示例以搜索其他目录

标签 c file-io glob

我目前正在使用一个代码示例,该示例最初旨在接受一个参数,然后在当前目录中搜索该参数,我试图通过替换“使其搜索另一个目录(精确到/ dev / shm)。 ”与“ / dev / shm”一起使用,但是当我搜索某些内容*时代码却没有显示(注意通配符)。通配符搜索在当前目录中可以正常工作,因此我认为不是通配符是问题所在,如果有人可以帮助我,尽管我真的很感谢,谢谢!

#include <dirent.h>
#include <errno.h>
#include <stdio.h>
#include <string.h>


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 %s\n", arg);
            (void) closedir(dirp);
                return;


        }
    } while (dp != NULL);


    if (errno != 0)
        perror("error reading directory");
    else
        (void) printf("failed to find %s\n", 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将首先展开通配符,然后执行您键入的命令。

那么如何解决呢?在调用glob之前,先使用opendir扩展通配符。



编辑:对不起,我以为您正在尝试匹配目录名称中的通配符。看起来您想使用通配符来匹配目录内容。在这种情况下,只需更换

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




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




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

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


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 %s\n", arg);
    } else {
        for (p = res.gl_pathv; n; p++, n--) {
            printf("found %s\n", *p);
        }
    }
    globfree(&res);
}


int main(int argc, char *argv[])
{
    int i;
    for (i = 2; i < argc; i++)
        lookup(argv[1], argv[i]);
    return (0);
}

关于c - 我如何获得此readdir代码示例以搜索其他目录,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10678522/

相关文章:

c - 网络编程 : what happen if network disconnect after select and before send

makefile 可以用来读取输入文件吗?

python - 将多个视频中的帧提取到多个文件夹中

c - (node v8plus)example.c :5:26: fatal error: sys/ccompile. h: 没有这样的文件或目录

c - 短类型可以在 C 中存储的最大和最小数字是多少?

c# - 删除文件锁

c# - 打开文件只读

java - 由于 Linux 中不同的挂载卷,文件移动抛出 IOException

regex - 如何使用正则表达式 (glob) 搜索文件树

regex - 为什么我无法在正则表达式中将某些字符串与 ( | ) 匹配