问题
Is there a ready-made function in C
that can list the contents of a directory using wildcards
to filter out file names, for example, the equivalent of:
echo [!b]????
which shows the names of directory entries that are four characters long and do not start with "b"?
I know I can use scandir
, but then, I need to provide my own filter function:
#include <stdio.h>
#include <stdlib.h>
#include <dirent.h>
int filter(const struct dirent *entry)
{
if (strlen(entry->d_name) == 4 && entry->d_name[0] != 'b') return 1;
else return 0;
}
void main(void)
{
struct dirent **list;
int count;
count=scandir(".", &list, filter, alphasort)-1;
if (count < 0)
puts("Cannot open directory");
else
for (; count >= 0; count--)
puts(list[count]->d_name);
free(list);
}
Honestly, I am seriously considering actually calling shell
to do it for me:
#include <stdio.h>
#include <stdlib.h>
void main(void)
{
FILE *fp;
char buffer[1024];
fp=popen("echo [!b]???", "r");
if (fp == NULL)
puts("Failed to run command.");
else
while (fgets(buffer, sizeof(buffer), fp) != NULL)
puts(buffer);
pclose(fp);
}
回答1:
As mentioned in the comments the glob()
function would be pretty good for this:
#include <stdio.h>
#include <glob.h>
int
main (void)
{
int i=0;
glob_t globbuf;
if (!glob("[!b]????", 0, NULL, &globbuf)) {
for (i=0; i <globbuf.gl_pathc; i++) {
printf("%s ",globbuf.gl_pathv[i]);
}
printf("\n");
globfree(&globbuf);
} else
printf("Error: glob()\n");
}
来源:https://stackoverflow.com/questions/38972164/directory-listing-with-wildcards-in-c