readdir2.py 875 B

123456789101112131415161718192021222324252627282930313233
  1. # A Linux-only demo, using verify() instead of hard-coding the exact layouts
  2. #
  3. import sys
  4. from _readdir2 import ffi, lib
  5. if not sys.platform.startswith('linux'):
  6. raise Exception("Linux-only demo")
  7. def walk(basefd, path):
  8. print '{', path
  9. dirfd = lib.openat(basefd, path, 0)
  10. if dirfd < 0:
  11. # error in openat()
  12. return
  13. dir = lib.fdopendir(dirfd)
  14. dirent = ffi.new("struct dirent *")
  15. result = ffi.new("struct dirent **")
  16. while True:
  17. if lib.readdir_r(dir, dirent, result):
  18. # error in readdir_r()
  19. break
  20. if result[0] == ffi.NULL:
  21. break
  22. name = ffi.string(dirent.d_name)
  23. print '%3d %s' % (dirent.d_type, name)
  24. if dirent.d_type == lib.DT_DIR and name != '.' and name != '..':
  25. walk(dirfd, name)
  26. lib.closedir(dir)
  27. print '}'
  28. walk(-1, "/tmp")