Re: dir() on linux via c_func, anyone?
- Posted by ghaberek (admin) Nov 28, 2016
- 1256 views
I haven't had a need for it per se, but you'd have to use the dirent.h functions.
Here's a quick wrapper around the struct and functions, and a port of the example provided here.
Hope this helps.
-- dirent.e namespace dirent include std/dll.e include std/machine.e include std/error.e export constant NULL = dll:NULL ifdef WINDOWS then error:crash( "Platform not supported by dirent.e" ) end ifdef ifdef BITS64 then export constant dirent__d_ino = 0, -- ino_t dirent__d_off = 8, -- off_t dirent__d_reclen = 16, -- unsigned short int dirent__d_type = 18, -- unsigned char dirent__d_name = 19, -- char[256] SIZEOF_DIRENT = 280, $ elsedef export constant dirent__d_ino = 0, -- ino_t dirent__d_off = 4, -- off_t dirent__d_reclen = 8, -- unsigned short int dirent__d_type = 10, -- unsigned char dirent__d_name = 11, -- char[256] SIZEOF_DIRENT = 272, $ end ifdef atom libc = open_dll( "libc.so.6" ) constant _closedir = define_c_func( libc, "closedir", {C_POINTER}, C_INT ), _opendir = define_c_func( libc, "opendir", {C_POINTER}, C_POINTER ), _readdir = define_c_func( libc, "readdir", {C_POINTER}, C_POINTER ), _rewinddir = define_c_proc( libc, "rewinddir", {C_POINTER} ), _seekdir = define_c_proc( libc, "seekdir", {C_POINTER,C_LONG} ), _telldir = define_c_func( libc, "telldir", {C_POINTER}, C_LONG ), $ public enum D_INO, D_OFF, D_RECLEN, D_TYPE, D_NAME, $ constant D_FILENO = D_INO public enum -- d_type DT_UNKNOWN = 0, DT_FIFO, DT_CHR, DT_DIR, DT_BLK, DT_REG, DT_LNK, DT_SOCK, DT_WHT, $ public function closedir( atom dirp ) return c_func( _closedir, {dirp} ) end function public function opendir( sequence dirname ) return c_func( _opendir, {allocate_string(dirname,1)} ) end function public function readdir( atom dirp ) return c_func( _readdir, {dirp} ) end function public procedure rewinddir( atom dirp ) c_proc( _rewinddir, {dirp} ) end procedure public procedure seekdir( atom dirp, atom loc ) c_proc( _seekdir, {dirp,loc} ) end procedure public function telldir( atom dirp ) return c_func( _telldir, {dirp} ) end function
-- listdir.ex include dirent.e function listdir( sequence path ) atom dirp, dirent dirp = opendir( path ) if dirp = NULL then puts( 2, "opendir\n" ) return -1 end if dirent = readdir( dirp ) while dirent != NULL do sequence name = peek_string( dirent + dirent__d_name ) printf( 1, "%s\n", {name} ) dirent = readdir( dirp ) end while closedir( dirp ) return 0 end function procedure main() sequence cmd = command_line() if length( cmd ) = 2 then listdir( "." ) end if for i = 3 to length( cmd ) do printf( 1, "\nListing %s...\n", {cmd[i]} ) listdir( cmd[i] ) end for end procedure main()
-Greg