0

I've been looking for a way to search for a file based on a pattern (*-stack.txt for example) over the last few days and have been having a very difficult time finding a way to do so, having said that I was wondering if anyone knew of a way to do this? Have searched around on google and such as well, but could not really find anything of use :/ this would just serve to search a linux directory for files that match a certain pattern

(an example of directory plus out)

/dev/shm/123-stack.txt abc-stack.txt overflow-stack.txt

searching for *-overflow.txt would return all of the above files 
lacrosse1991
  • 2,972
  • 7
  • 38
  • 47

2 Answers2

1

Your best bet is probably glob(3). It does almost exactly what you want. From what you've said a sketch of the proper code is

char glob_pattern[PATH_MAX];
glob_t glob_result;
snprintf(glob_pattern, PATH_MAX, "%s/%s", directory, file_pattern);
glob(glob_pattern, 0, NULL, &glob_result);
for (size_t i = 0; i < glob_result.gl_pathc; ++i) {
  char *path = glob_result.gl_pathv[i];
  /* process path */
}
Geoff Reedy
  • 34,891
  • 3
  • 56
  • 79
0

I think you should use the opendir system call, like it's described in this question.

But it's going to be a lot more work on top of that - hence higher-level languages providing better interfaces.

Community
  • 1
  • 1
Rob I
  • 5,627
  • 2
  • 21
  • 28