0

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

2
  • 1
    What OS? Or do you need a cross-platform solution? Commented Apr 5, 2014 at 20:39
  • 1
    Look into opendir readdir and glob Commented Apr 5, 2014 at 20:39

2 Answers 2

3

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; } 
Sign up to request clarification or add additional context in comments.

3 Comments

Why is having to free() memory a downside? That's what has to be done all the day...
What I am trying to say is that sometimes a programmer forgets to free the memory or unaware he/she should free the memory since it is allocated by scandir not the programmer himself/herself.
That is right, but holds for all kinds of memory allocations. Maybe the wording could be "The only thing to consider" or "to remember"...
2

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)

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.