【问题标题】:get list of file names and store them in array on linux using C使用C获取文件名列表并将它们存储在Linux上的数组中
【发布时间】:2013-10-07 16:02:56
【问题描述】:

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


【解决方案1】:

以下程序可以帮助您。 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);
}

【讨论】:

  • 虽然,我已经吃光了内存,但它会为你工作。
  • 这是未定义的行为。用 0 初始化 count
猜你喜欢
  • 1970-01-01
  • 2013-06-25
  • 2017-10-13
  • 2019-09-05
  • 1970-01-01
  • 1970-01-01
  • 2012-11-27
  • 2021-06-09
  • 2020-09-17
相关资源
最近更新 更多