Question

I have to program a shell in C and need to handle globing in it and I am only allowed to use the function glob. But when I try to use it, it only gives me one result back.

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

int     main(int ac, char **av)
{
  glob_t    s;
  unsigned long  i = -1;

  if (glob(av[1], 0, NULL, &s))
    printf("ERROR !\n");
  else
    while (++i < s.gl_pathc)
      printf("%s\n", s.gl_pathv[i]);
  return (0);
}

I run this code in a folder where there is two C files : replace_glob.c and test.c

And when I run this code :

$ ./a.out *.c
replace_glob.c
$ 

I dont understand why and I would really appreciate your help

Was it helpful?

Solution

In the command line

./a.out *.c

the shell expands the glob pattern, so your program sees

{"./a.out", "replace_glob.c", "test.c", NULL}

as its argv. You need to quote the pattern for the program to see it:

./a.out '*.c'
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top