1

i have a problem with the usage of wordexp. If this function cannot find any files, it returns like it had found 1.

#include <stdio.h>
#include <wordexp.h>
#include <string.h>

int main(int argc, char* argv[])
{
    if (argc < 2)
        return -1;

    printf("searching for %s:\n", argv[1]);
    wordexp_t p;
    memset(&p, 0, sizeof p);
    if (wordexp(argv[1], &p, 0) != 0)
        return -1;

    char **w = p.we_wordv;
    printf("p.we_offs = %zu\n", p.we_offs);
    printf("p.we_wordc = %zu\n", p.we_wordc);

    for (unsigned int i = 0; i < p.we_wordc; i++)
    {
        printf("file found: %s\n", w[i]);
    }

    wordfree(&p);
    return 0;
}

Calling this program with ./a.out "test*.c" results in

searching for test*.c:
p.we_offs = 0
p.we_wordc = 2
file found: test1.c
file found: test2.c

but calling it with ./a.out "test0*.c" results in

searching for test0*.c:
p.we_offs = 0
p.we_wordc = 1
file found: test0*.c

should not be p.we_wordc equal to 0, because no file is found?

thanks in advance

mch
  • 9,424
  • 2
  • 28
  • 42
  • 2
    The definition of [`wordexp()`](http://pubs.opengroup.org/onlinepubs/9699919799/functions/wordexp.html) says "do what the shell does" and the POSIX shell returns `test0*.c` when there are no commands that match `test0*.c`, so that's what `wordexp()` does. Bash has `shopt -s nullglob` to change this behaviour. – Jonathan Leffler Jan 22 '15 at 17:41
  • 1
    For your C program, however, you may want to use `glob(3)` instead of `wordexp(3)`, in particular looking at the GLOB_NOCHECK flag and GLOB_NOMATCH return value. – mpez0 Jan 22 '15 at 20:39
  • thanks for the hints, i will use `glob` to avoid this problem. – mch Jan 26 '15 at 10:53

0 Answers0