【问题标题】:Directory listing with wildcards in CC中带有通配符的目录列表
【发布时间】:2016-12-22 16:00:44
【问题描述】:

C中是否有现成的函数可以列出目录的内容,使用wildcards过滤掉文件名,例如相当于:

echo [!b]????

显示四个字符长且不以“b”开头的目录条目的名称?

我知道我可以使用scandir,但是,我需要提供自己的过滤功能:

#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);
}

老实说,我正在认真考虑打电话给shell 为我做这件事:

#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);
}

【问题讨论】:

  • 在函数过滤器中使用正则表达式有什么问题?
  • 我需要 ls wildcard 行为,这与正则表达式不太一样。例如:*.jpg 的意思是“任意数量的任意字符,后跟 dot-jpg”,而在正则表达式中,它的意思是“任意数量的空,后跟一个任意类型的字符,然后是 jpg”。正则表达式等效于 .*\.jpg,不是吗?
  • 您可能正在寻找glob 函数。 man 3 glob.
  • 你看过fnmatch()wordexp()glob()吗?
  • 谢谢! fnmatchglob 对于我所拥有的不同场景都会很有用。

标签: c linux filter directory scandir


【解决方案1】:

正如 cmets 中提到的,glob() 函数非常适合:

#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");
}

【讨论】:

    猜你喜欢
    • 2015-07-17
    • 1970-01-01
    • 2012-12-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-09-17
    • 2018-01-02
    相关资源
    最近更新 更多