Reputation: 3162
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
Upvotes: 0
Views: 152
Reputation: 36011
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 */
}
Upvotes: 1
Reputation: 5737
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.
Upvotes: 0