Subversion Repositories Tewi

Rev

Rev 212 | Rev 219 | Go to most recent revision | Details | Compare with Previous | Last modification | View Log | RSS feed

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