lacrosse1991
lacrosse1991

Reputation: 3162

how can I search for a file using C

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

Answers (2)

Geoff Reedy
Geoff Reedy

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

Rob I
Rob I

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

Related Questions