How to get a directory file descriptor?

Cong Ma cma at mail.bnu.edu.cn
Wed Nov 26 09:04:53 EST 2008


Nick Craig-Wood wrote:
> Here is how you do exactly that in python using ctypes
> 
> from ctypes import CDLL, c_char_p, c_int, Structure, POINTER
> from ctypes.util import find_library
> 
> class c_dir(Structure):
>     """Opaque type for directory entries, corresponds to struct DIR"""
> c_dir_p = POINTER(c_dir)
> 
> c_lib = CDLL(find_library("c"))
> opendir = c_lib.opendir
> opendir.argtypes = [c_char_p]
> opendir.restype = c_dir_p
> dirfd = c_lib.dirfd
> dirfd.argtypes = [c_dir_p]
> dirfd.restype = c_int
> closedir = c_lib.closedir
> closedir.argtypes = [c_dir_p]
> closedir.restype = c_int
> 
> dir_p = opendir(".")
> print "dir_p = %r" % dir_p
> dir_fd = dirfd(dir_p)
> print "dir_fd = %r" % dir_fd
> print "closed (rc %r)" % closedir(dir_p)
> 
> Which prints on my linux machine
> 
> dir_p = <ctypes.LP_c_dir object at 0xb7d13cd4>
> dir_fd = 3
> closed (rc 0)
> 
> I don't know why os doesn't wrap - opendir, closedir, dirfd, readdir
> etc - I guess because except if you are doing something esoteric, then
> os.list and os.walk do everything you could possibly want.
> 

Thank you so much Nick. I'll take a look into the ctypes module.

I guess the reason of Python library not including those wrappers has something
to do with standard compliance. The fchdir(2) manual says "comforming to
POSIX.1-2001" but the opendir(3) manual says "fdopendir() is specified in
POSIX.1-2008."




More information about the Python-list mailing list