Directory listing with wildcards in C

扶醉桌前 提交于 2019-12-11 02:36:20

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!