user3343456
user3343456

Reputation: 103

C get all files with certain extension

How to find all extensions in a directory with a ".ngl" extension?

Upvotes: 0

Views: 8338

Answers (2)

SSC
SSC

Reputation: 1331

If you want to get the list of file name with the same extension in a folder with one system call, you can try to use scandir instead of using opendir and readdir. The only thing to remember is that you need to free the memory allocate by scandir.

   /* print files in current directory with specific file extension */
   #include <string.h>
   #include <stdio.h>
   #include <stdlib.h>
   #include <dirent.h>

   /* when return 1, scandir will put this dirent to the list */
   static int parse_ext(const struct dirent *dir)
   {
     if(!dir)
       return 0;

     if(dir->d_type == DT_REG) { /* only deal with regular file */
         const char *ext = strrchr(dir->d_name,'.');
         if((!ext) || (ext == dir->d_name))
           return 0;
         else {
           if(strcmp(ext, ".ngl") == 0)
             return 1;
         }
     }

     return 0;
   }

   int main(void)
   {
       struct dirent **namelist;
       int n;

       n = scandir(".", &namelist, parse_ext, alphasort);
       if (n < 0) {
           perror("scandir");
           return 1;
       }
       else {
           while (n--) {
               printf("%s\n", namelist[n]->d_name);
               free(namelist[n]);
           }
           free(namelist);
       }

       return 0;
   }

Upvotes: 3

user3185968
user3185968

Reputation:

C doesn't have standardised directory management, that's POSIX (or Windows if you're so inclined).
In POSIX, you can do something like:

  1. Take the char * that contains the path to the directory
  2. use opendir() on it, you get a DIR *
  3. using readdir() on the DIR * repeatedly gives you the entries struct dirent* in the directory
  4. the stuct dirent* contains the name of the file, including the extension (.ngl). It also contains info on whether the entry is a regular file or something else (a symlink, subdirectory, whatever)

Upvotes: 2

Related Questions