Wildcards in C
- October 25th, 2010
- By admin
- Write comment
As I have been using the command line more recently, I have started to wonder many things. One of the most commonly used thing throughout command-line applications is wildcards. That is, replacing part of a search with a *, or deleting all the files that end with a .c. Since wildcards are so useful, I figured I would make my own wildcard program to see how easy it was to make.
My method of wildcard-checking is as follows: loop through the pattern until you see a * while checking regular characters with the other string. If I find a ‘*’, I find all of the characters until the end of string. I then check to see where the last occurrence of that pattern is in the regular string. If I find it, I go from there. This is not an easy thing to understand in english, so take a look at the C code at my Git repository for it: BasicWildcards
[UPDATE]: One of our readers commented on this post with information on how command-line apps do it. There is a function called glob() (declared in glob.h) that filters files that match a simple pattern. Since I am sure you are wondering how this works, check out this little example:
#include <stdio.h>
#include <glob.h>
int main () {
glob_t g;
int i;
glob("*.php", GLOB_ERR | GLOB_NOSORT, NULL, &g);
for (i = 0; i < g.gl_matchc; i++) {
printf("%s\n", g.gl_pathv[i]);
}
}
