Rev | Line | |
---|
[21] | 1 | /* $Id: dir.c 22 2024-09-14 13:25:38Z nishi $ */
|
---|
| 2 |
|
---|
| 3 | #include "cm_dir.h"
|
---|
| 4 |
|
---|
| 5 | #include "cm_string.h"
|
---|
| 6 |
|
---|
| 7 | #include <sys/stat.h>
|
---|
| 8 | #include <dirent.h>
|
---|
| 9 | #include <stdlib.h>
|
---|
| 10 | #include <string.h>
|
---|
| 11 |
|
---|
[22] | 12 | int cm_sort(const void* _a, const void* _b) {
|
---|
[21] | 13 | char* a = *(char**)_a;
|
---|
| 14 | char* b = *(char**)_b;
|
---|
| 15 | return strcmp(a, b);
|
---|
| 16 | }
|
---|
| 17 |
|
---|
[22] | 18 | char** cm_scandir(const char* path) {
|
---|
[21] | 19 | DIR* dir = opendir(path);
|
---|
[22] | 20 | if(dir != NULL) {
|
---|
[21] | 21 | char** r = malloc(sizeof(*r));
|
---|
| 22 | r[0] = NULL;
|
---|
| 23 | struct dirent* d;
|
---|
[22] | 24 | while((d = readdir(dir)) != NULL) {
|
---|
| 25 | if(strcmp(d->d_name, ".") != 0 && strcmp(d->d_name, "..") != 0) {
|
---|
[21] | 26 | struct stat s;
|
---|
| 27 | char* p = cm_strcat3(path, "/", d->d_name);
|
---|
| 28 | stat(p, &s);
|
---|
| 29 | free(p);
|
---|
| 30 |
|
---|
| 31 | char** old = r;
|
---|
| 32 | int i;
|
---|
[22] | 33 | for(i = 0; old[i] != NULL; i++)
|
---|
| 34 | ;
|
---|
[21] | 35 | r = malloc(sizeof(*r) * (i + 2));
|
---|
| 36 | for(i = 0; old[i] != NULL; i++) r[i] = old[i];
|
---|
| 37 | r[i] = cm_strcat(d->d_name, S_ISDIR(s.st_mode) ? "/" : "");
|
---|
| 38 | r[i + 1] = NULL;
|
---|
| 39 | free(old);
|
---|
| 40 | }
|
---|
| 41 | }
|
---|
| 42 | int len;
|
---|
[22] | 43 | for(len = 0; r[len] != NULL; len++)
|
---|
| 44 | ;
|
---|
[21] | 45 | qsort(r, len, sizeof(char*), cm_sort);
|
---|
[22] | 46 |
|
---|
| 47 | char** old = r;
|
---|
| 48 | int i;
|
---|
| 49 | for(i = 0; old[i] != NULL; i++)
|
---|
| 50 | ;
|
---|
| 51 | r = malloc(sizeof(*r) * (i + 2));
|
---|
| 52 | for(i = 0; old[i] != NULL; i++) r[i + 1] = old[i];
|
---|
| 53 | r[0] = cm_strdup("../");
|
---|
| 54 | r[i + 1] = NULL;
|
---|
| 55 | free(old);
|
---|
| 56 |
|
---|
[21] | 57 | return r;
|
---|
[22] | 58 | } else {
|
---|
[21] | 59 | return NULL;
|
---|
| 60 | }
|
---|
| 61 | }
|
---|
Note:
See
TracBrowser
for help on using the repository browser.