【发布时间】:2014-04-05 20:20:14
【问题描述】:
如何在带有“.ngl”扩展名的目录中查找所有扩展名?
【问题讨论】:
-
什么操作系统?还是您需要跨平台解决方案?
-
查看 opendir readdir 和 glob
如何在带有“.ngl”扩展名的目录中查找所有扩展名?
【问题讨论】:
C 没有标准化的目录管理,即 POSIX(或 Windows,如果您愿意的话)。
在 POSIX 中,您可以执行以下操作:
char *opendir(),你会得到一个DIR * DIR * 上反复使用readdir() 会为您提供目录中的struct dirent* 条目stuct dirent* 包含文件的名称,包括扩展名 (.ngl)。它还包含有关条目是常规文件还是其他内容(符号链接、子目录等)的信息【讨论】:
如果你想通过一个系统调用获取文件夹中具有相同扩展名的文件名列表,你可以尝试使用scandir,而不是使用opendir和readdir。唯一要记住的是,您需要释放由scandir 分配的内存。
/* print files in current directory with specific file extension */
#include <string.h>
#include <stdio.h>
#include <stdlib.h>
#include <dirent.h>
/* when return 1, scandir will put this dirent to the list */
static int parse_ext(const struct dirent *dir)
{
if(!dir)
return 0;
if(dir->d_type == DT_REG) { /* only deal with regular file */
const char *ext = strrchr(dir->d_name,'.');
if((!ext) || (ext == dir->d_name))
return 0;
else {
if(strcmp(ext, ".ngl") == 0)
return 1;
}
}
return 0;
}
int main(void)
{
struct dirent **namelist;
int n;
n = scandir(".", &namelist, parse_ext, alphasort);
if (n < 0) {
perror("scandir");
return 1;
}
else {
while (n--) {
printf("%s\n", namelist[n]->d_name);
free(namelist[n]);
}
free(namelist);
}
return 0;
}
【讨论】:
free() 内存是一个缺点?这就是整天必须做的事情......
scandir而不是程序员自己分配的。跨度>