File: readdir2.py

package info (click to toggle)
python-cffi 2.0.0~b1-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 2,796 kB
  • sloc: python: 28,456; ansic: 15,272; asm: 116; makefile: 97; sh: 14
file content (36 lines) | stat: -rw-r--r-- 1,002 bytes parent folder | download
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
from __future__ import print_function
# A Linux-only demo, using set_source() instead of hard-coding the exact layouts
#
import sys

if not sys.platform.startswith('linux'):
    raise Exception("Linux-only demo")

# run readdir2_build first, then make sure the shared object is on sys.path
from _readdir2_cffi import ffi, lib


def walk(basefd, path):
    print('{', path)
    dirfd = lib.openat(basefd, path, 0)
    if dirfd < 0:
        # error in openat()
        return
    dir = lib.fdopendir(dirfd)
    dirent = ffi.new("struct dirent *")
    result = ffi.new("struct dirent **")
    while True:
        if lib.readdir_r(dir, dirent, result):
            # error in readdir_r()
            break
        if result[0] == ffi.NULL:
            break
        name = ffi.string(dirent.d_name)
        print('%3d %s' % (dirent.d_type, name))
        if dirent.d_type == lib.DT_DIR and name != '.' and name != '..':
            walk(dirfd, name)
    lib.closedir(dir)
    print('}')


walk(-1, "/tmp")