How to find all extensions in a directory with a ".ngl" extension?
2 Answers
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; } 3 Comments
glglgl
Why is having to
free() memory a downside? That's what has to be done all the day...SSC
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.glglgl
That is right, but holds for all kinds of memory allocations. Maybe the wording could be "The only thing to consider" or "to remember"...
C doesn't have standardised directory management, that's POSIX (or Windows if you're so inclined).
In POSIX, you can do something like:
- Take the
char *that contains the path to the directory - use
opendir()on it, you get aDIR * - using
readdir()on theDIR *repeatedly gives you the entriesstruct dirent*in the directory - 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)