有什么方法可以在目录中查找具有给定模式的文件名并将这些文件名(可能存储在数组中)存储在Linux上的C语言中?
我尝试了一个glob,但是除了打印出来之外,我不知道该如何保存它们的名称。
glob_t g;
g.gl_offs = 2;
glob("*.c", GLOB_DOOFFS | GLOB_APPEND, NULL, &g);
g.gl_pathv[0] = "ls";
g.gl_pathv[1] = "-l";
execvp("ls", g.gl_pathv);
以下程序可以为您提供帮助。如何在C程序的目录中列出文件?
之后,一旦显示文件。在显示功能中-printf-复制数组中的文件名。我想文件名大小有一个限制,所以可以是数组的最大大小。如果要保存内存,则可以使用realloc并可以创建确切数量的字符数组。
这是获取数据的快捷方式。
#include <dirent.h>
#include <stdio.h>
char name[256][256];
int main(void)
{
DIR *d;
struct dirent *dir;
int count = 0;
int index = 0;
d = opendir(".");
if (d)
{
while ((dir = readdir(d)) != NULL)
{
printf("%s\n", dir->d_name);
strcpy(name[count],dir->d_name);
count++;
}
closedir(d);
}
while( count > 0 )
{
printf("The directory list is %s\r\n",name[index]);
index++;
count--;
}
return(0);
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句