C获取具有特定扩展名的所有文件 [英] C get all files with certain extension
本文介绍了C获取具有特定扩展名的所有文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
如何在扩展名为".ngl"的目录中查找所有扩展名?
How to find all extensions in a directory with a ".ngl" extension?
推荐答案
如果要通过一个系统调用在一个文件夹中获取具有相同扩展名的文件名列表,则可以尝试使用 scandir 代码>而不是使用
opendir
和 readdir
.唯一要记住的是,您需要释放 scandir
分配的内存.
If you want to get the list of file name with the same extension in a folder with one system call, you can try to use scandir
instead of using opendir
and readdir
. The only thing to remember is that you need to free the memory allocate by 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;
}
这篇关于C获取具有特定扩展名的所有文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文