| 1 |
/* this file contains experimental XS stuff I'm working on */ |
| 2 |
/* |
| 3 |
I'd like to be able to grab the dir handle coming in and get its |
| 4 |
fileno (IO::Dir::Dirfd has some sample code that might be useful). |
| 5 |
|
| 6 |
The reason I'd like to do that is so I can stat each entry in the |
| 7 |
dir (and get the file type) if DT_DIR is not implemented. |
| 8 |
*/ |
| 9 |
|
| 10 |
#include "EXTERN.h" |
| 11 |
#include "perl.h" |
| 12 |
#include "XSUB.h" |
| 13 |
|
| 14 |
#include <sys/types.h> |
| 15 |
#include <dirent.h> |
| 16 |
|
| 17 |
MODULE = IO::Dirent PACKAGE = IO::Dirent |
| 18 |
|
| 19 |
#ifdef DT_DIR2 |
| 20 |
#define USE_D_NAME |
| 21 |
#endif |
| 22 |
|
| 23 |
SV * |
| 24 |
readdirent(dirh) |
| 25 |
SV *dirh = ST(0); |
| 26 |
PROTOTYPE: * |
| 27 |
PREINIT: |
| 28 |
IO *io; |
| 29 |
INIT: |
| 30 |
DIR *dirp = IoDIRP(sv_2io(dirh)); |
| 31 |
Direntry_t *dent; |
| 32 |
#ifndef USE_D_NAME |
| 33 |
int dirfp = fileno(dirfd(IoDIRP(sv_2io(dirh)))); |
| 34 |
int fdsave; /* cwd to return to */ |
| 35 |
struct stat sb; |
| 36 |
#endif |
| 37 |
PPCODE: |
| 38 |
#ifndef USE_D_NAME |
| 39 |
/* save an fd of our current working directory */ |
| 40 |
if( fdsave = open(".", O_RDONLY) < 0 ) { |
| 41 |
XSRETURN_UNDEF; |
| 42 |
} |
| 43 |
|
| 44 |
if( dirfp ) { |
| 45 |
fprintf(stderr, "ok!\n"); |
| 46 |
} |
| 47 |
else { |
| 48 |
fprintf(stderr, "not ok!\n"); |
| 49 |
} |
| 50 |
/* chdir to directory we're reading */ |
| 51 |
if( fchdir(dirfp) == 0 ) { |
| 52 |
fprintf(stderr, "Hi!\n"); |
| 53 |
#endif |
| 54 |
while ((dent = (Direntry_t *)readdir(dirp))) { |
| 55 |
HV *hdent; |
| 56 |
hdent = (HV *)sv_2mortal((SV *)newHV()); |
| 57 |
#ifdef DIRNAMLEN |
| 58 |
hv_store(hdent, "name", 4, newSVpv(dent->d_name, dent->d_namlen), 0); |
| 59 |
#else |
| 60 |
hv_store(hdent, "name", 4, newSVpv(dent->d_name, 0), 0); |
| 61 |
#endif /* DIRNAMLEN */ |
| 62 |
#ifdef USE_D_NAME |
| 63 |
hv_store(hdent, "type", 4, newSVnv(dent->d_type), 0); |
| 64 |
#else |
| 65 |
if( lstat(dent->d_name, &sb) == 0 ) { |
| 66 |
hv_store(hdent, "type", 4, newSVnv( ( ((sb.st_mode) & 0170000) >> 12) ), 0); |
| 67 |
} |
| 68 |
#endif |
| 69 |
XPUSHs(sv_2mortal(newRV((SV *) hdent))); /* test this w/o newRV */ |
| 70 |
} |
| 71 |
#ifndef USE_D_NAME |
| 72 |
fclose(fdsave); |
| 73 |
} |
| 74 |
else { |
| 75 |
switch(errno) { |
| 76 |
case EACCES: |
| 77 |
fprintf(stderr, "Access denied.\n"); |
| 78 |
break; |
| 79 |
case ENOTDIR: |
| 80 |
fprintf(stderr, "Directory does not exist.\n"); |
| 81 |
break; |
| 82 |
case EBADF: |
| 83 |
fprintf(stderr, "Not a valid file descriptor.\n"); |
| 84 |
break; |
| 85 |
default: |
| 86 |
fprintf(stderr, "Some other error.\n"); |
| 87 |
break; |
| 88 |
} |
| 89 |
} |
| 90 |
#endif |