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:
C中是否有现成的函数,可以使用通配符来列出目录的内容来过滤文件名,例如:
echo [!b]????
which shows the names of directory entries that are four characters long and do not start with "b"?
显示4个字符长且不以“b”开头的目录项的名称?
I know I can use scandir
, but then, I need to provide my own filter function:
我知道我可以使用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);
}
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 个解决方案
#1
2
As mentioned in the comments the glob()
function would be pretty good for this:
如评论中所提到的,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");
}
#1
2
As mentioned in the comments the glob()
function would be pretty good for this:
如评论中所提到的,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");
}