1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
|
#include <Python.h>
#include <dirent.h>
#include <iostream>
#include <string>
#include <vector>
/*
==============================================================================
This is the original function in python
def _build_tree(self,path):
l = []
for fn in os.listdir(path):
try: p = os.path.join(path, fn)
except: continue
s = os.lstat(p)
if stat.S_ISDIR(s.st_mode): l.append( (fn, self._build_tree(p)) )
elif stat.S_ISREG(s.st_mode): l.append( (fn, s.st_size) )
return sum_list(l, os.path.split(path)[-1])
==============================================================================
Instead of using SumList, the new build_tree will use a tuple
*/
/// recursive function to build a list system with directory information
PyObject* build_tree( std::string path, const bool& skipHidden) {
PyObject* l = PyList_New(0);
DIR* d = opendir(path.c_str());
struct dirent *e;
int total = 0;
while((e = readdir(d)) != NULL) {
std::string fn = e->d_name;
if(skipHidden) if(e->d_name[0] == '.') continue;
if(fn == "." || fn == "..") continue;
fn = path+"/" +fn;
struct stat s;
lstat(fn.c_str(), &s);
if(S_ISDIR(s.st_mode)) {
PyObject* sub = build_tree(fn,skipHidden);
PyList_Append(l, sub );
total += PyInt_AsLong( PyTuple_GET_ITEM(sub,2) );
} else if (S_ISREG(s.st_mode)) {
PyList_Append(l, Py_BuildValue("(sOi)",fn.c_str(),Py_None,s.st_size) );
total += s.st_size;
}
}
closedir(d);
return Py_BuildValue("(sOi)", path.c_str(), l, total );
}
/// initial function call.
static PyObject* fringtools_build_tree(PyObject *self, PyObject *args) {
const char *path;
int skip_hidden = 1;
if (!PyArg_ParseTuple(args, "si", &path, &skip_hidden)) return NULL;
PyObject* o;
//Py_BEGIN_ALLOW_THREADS
o = build_tree(std::string(path),(skip_hidden==1));
//Py_END_ALLOW_THREADS
return o;
}
//==============================================================================
// module init
//==============================================================================
static PyMethodDef FringtoolsMethods[] = {
{"build_tree", fringtools_build_tree, METH_VARARGS, "Walk Tree."},
{NULL, NULL, 0, NULL} /* Sentinel */
};
PyMODINIT_FUNC initfringtools(void) {
(void) Py_InitModule("fringtools", FringtoolsMethods);
}
int main(int argc, char *argv[]) {
Py_SetProgramName(argv[0]);
Py_Initialize();
initfringtools();
return 0;
}
|