Search code examples
clinuxlistfilenamesglob

get list of file names and store them in array on linux using C


is there any way to look for some file names with given pattern in a directory and store those names (probably in an array) in C on Linux?

I tried the glob one but I dont know how to save the names besides just print them out..

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);

Solution

  • The following program can help you. How to list files in a directory in a C program?

    Afterwards, once the file is displayed. In the display function - printf - Copy the filenames in the array. I guess there is a restriction on the filename size.So that can be the maximum size of the array. In case, you want to save the memory, then you can use realloc and can create the exact number of characters array.

    This is a shortcut way to get the data.

    #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);
    }