在C中使用通配符的目录列表 [英] Directory listing with wildcards in C
本文介绍了在C中使用通配符的目录列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
C
中是否有现成的函数,可以使用wildcards
列出目录内容以过滤出文件名,例如,等效于:
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]????
其中显示的目录条目的名称是四个字符,并且不以"b"开头?
which shows the names of directory entries that are four characters long and do not start with "b"?
我知道我可以使用scandir
,但是随后,我需要提供自己的过滤器功能:
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);
}
老实说,我正在认真考虑实际打电话给shell
为我做的事情:
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);
}
推荐答案
如注释中所述,glob()
函数对此非常有用:
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");
}
这篇关于在C中使用通配符的目录列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文