source: Main/trunk/Common/dir.c@ 309

Last change on this file since 309 was 292, checked in by Nishi, on Oct 9, 2024 at 7:49:15 PM

c89

  • Property svn:keywords set to Id
File size: 2.4 KB
Line 
1/* $Id: dir.c 292 2024-10-09 10:49:15Z nishi $ */
2
3#include "cm_dir.h"
4
5#include "cm_string.h"
6
7#include <sys/stat.h>
8#if !defined(_MSC_VER) && !defined(__WATCOMC__)
9#include <dirent.h>
10#elif defined(__WATCOMC__) || defined(_MSC_VER)
11#include <direct.h>
12#endif
13#ifdef _MSC_VER
14#include <windows.h>
15#endif
16#include <stdlib.h>
17#include <string.h>
18
19int cm_sort(const void* _a, const void* _b) {
20 char* a = *(char**)_a;
21 char* b = *(char**)_b;
22 return strcmp(a, b);
23}
24
25char** cm_scandir(const char* path) {
26#if defined(_MSC_VER) || defined(__BORLANDC__)
27 WIN32_FIND_DATA ffd;
28 HANDLE hfind;
29 char** r = malloc(sizeof(*r));
30 int len;
31 char** old;
32 int i;
33 char* p;
34 r[0] = NULL;
35
36 p = cm_strcat(path, "/*");
37 hfind = FindFirstFile(p, &ffd);
38 if(INVALID_HANDLE_VALUE == hfind) {
39 return NULL;
40 }
41 do {
42 if(strcmp(ffd.cFileName, ".") != 0 && strcmp(ffd.cFileName, "..") != 0) {
43 old = r;
44 for(i = 0; old[i] != NULL; i++)
45 ;
46 r = malloc(sizeof(*r) * (i + 2));
47 for(i = 0; old[i] != NULL; i++) r[i] = old[i];
48 r[i] = cm_strcat(ffd.cFileName, (ffd.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) ? "/" : "");
49 r[i + 1] = NULL;
50 free(old);
51 }
52 } while(FindNextFile(hfind, &ffd) != 0);
53 FindClose(hfind);
54 free(p);
55 for(len = 0; r[len] != NULL; len++)
56 ;
57 qsort(r, len, sizeof(char*), cm_sort);
58
59 old = r;
60 for(i = 0; old[i] != NULL; i++)
61 ;
62 r = malloc(sizeof(*r) * (i + 2));
63 for(i = 0; old[i] != NULL; i++) r[i + 1] = old[i];
64 r[0] = cm_strdup("../");
65 r[i + 1] = NULL;
66 free(old);
67
68 return r;
69#else
70 DIR* dir = opendir(path);
71 if(dir != NULL) {
72 char** r = malloc(sizeof(*r));
73 struct dirent* d;
74 char** old;
75 int len;
76 int i;
77 r[0] = NULL;
78 while((d = readdir(dir)) != NULL) {
79 if(strcmp(d->d_name, ".") != 0 && strcmp(d->d_name, "..") != 0) {
80 struct stat s;
81 char* p = cm_strcat3(path, "/", d->d_name);
82 stat(p, &s);
83 free(p);
84
85 old = r;
86 for(i = 0; old[i] != NULL; i++)
87 ;
88 r = malloc(sizeof(*r) * (i + 2));
89 for(i = 0; old[i] != NULL; i++) r[i] = old[i];
90 r[i] = cm_strcat(d->d_name, S_ISDIR(s.st_mode) ? "/" : "");
91 r[i + 1] = NULL;
92 free(old);
93 }
94 }
95 for(len = 0; r[len] != NULL; len++)
96 ;
97 qsort(r, len, sizeof(char*), cm_sort);
98
99 old = r;
100 for(i = 0; old[i] != NULL; i++)
101 ;
102 r = malloc(sizeof(*r) * (i + 2));
103 for(i = 0; old[i] != NULL; i++) r[i + 1] = old[i];
104 r[0] = cm_strdup("../");
105 r[i + 1] = NULL;
106 free(old);
107
108 closedir(dir);
109
110 return r;
111 } else {
112 return NULL;
113 }
114#endif
115}
Note: See TracBrowser for help on using the repository browser.