c - 使用C获取文件名列表并将它们存储在Linux上的数组中

标签 c linux list filenames glob

有什么方法可以在目录中查找具有给定模式的一些文件名并将这些名称(可能在数组中)存储在 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/

相关文章:

c - Linux C - 将 `iphdr->daddr` 转换为等效字符串 - 不再起作用了吗?

c - 如何将 web_reg_save_param 函数返回的每个值与 Load Runner 中的另一个参数进行比较

c++ - POD 和模板

c++ - 为什么我在函数中创建的对象不会被其他函数修改? (C++)

java - Vector 与 SynchronizedList 性能

c++ - 从 C 代码调用具有复杂参数和复杂返回类型的 C++ 函数

c - 如何实现日志?

Linux 功能 (setcap) 似乎禁用了 LD_LIBRARY_PATH

python - 调试 Python 崩溃

c# - 如果删除元素,List<T> 会缩小大小