Search code examples
cposixgloblibc

POSIX: glob() only finds first match


I have difficulties figuring out how to properly use the glob() function.

This is my simple test code:

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

int main(int argc, char *argv[])
{
    char *path;
    if (argc > 1) {
        path = argv[1];
    } else {
        path = "/foo/bar/";
    }
    glob_t pglob;
    int glob_res = glob(path, 0, NULL, &pglob);

    switch (glob_res) {
    case GLOB_ABORTED:
        printf("Glob failed: read error\n");
        break;
    case GLOB_NOMATCH:
        printf("Glob failed: no match\n");
        break;
    case GLOB_NOSPACE:
        printf("Glob failed: oom\n");
        break;
    default:
        printf("Matches: %lu\n", pglob.gl_pathc);
        for (unsigned i = 0; i < pglob.gl_pathc; ++i) {
            printf("%s\n", pglob.gl_pathv[i]);
        }
        break;
    }
    return 0;
}

Suppose I have a directory like this:

$ ls
a  b  glob  glob.c

I would expect a call to ./glob * to print all 4 files, however it just tells me about the first one:

$ ./glob *
Matches: 1
a

What silly beginner's mistake am I making?


Solution

  • As pointed out in the comments: the shell already did the globbing:

    ./glob * was resolved to ./glob a b glob glob.c and therefore the call to the glob() function used just a as pattern.

    Calling ./glob '*' solved the problem.