 ! An easy way to return +unknown+ is to mount a .iso on OSX and
 ! call directory-entries on the mount point.
 
-: next-dirent ( DIR* dirent* -- dirent* ? )
-    f void* <ref> [
-        readdir_r [ (throw-errno) ] unless-zero
-    ] 2keep void* deref ; inline
+: next-dirent ( DIR* -- dirent*/f )
+    readdir dup [
+        errno dup ENOENT = [ drop ] [ (throw-errno) ] if
+    ] unless ; inline
 
 : >directory-entry ( dirent* -- directory-entry )
     [ d_name>> alien>native-string ]


M: unix (directory-entries)
    [
        dirent new
        '[ _ _ next-dirent ] [ >directory-entry ] produce nip
    ] with-unix-directory ;

os linux? [ "io.directories.unix.linux" require ] when

    [ call-next-method ]
    [ [ file-permissions ] dip swap set-file-permissions ] 2bi ;

: with-unix-directory ( ..a path quot: ( ..a DIR* -- ..b ) -- ..b )
    dupd '[ _ _
        [ opendir dup [ throw-errno ] unless ] dip
        dupd curry swap '[ _ closedir io-error ] finally
