有什么方法可以在目录中查找具有给定模式的一些文件名并将这些名称(可能在数组中)存储在 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);
最佳答案
以下程序可以帮助您。 How to list files in a directory in a C program?
然后,一旦文件显示出来。在显示函数中 - 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);
}
关于c - 使用C获取文件名列表并将它们存储在Linux上的数组中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19117131/