lib: adds function to list files within a directory
authorAlexis Laferrière <alexis.laf@xymus.net>
Fri, 24 Feb 2012 16:47:28 +0000 (11:47 -0500)
committerAlexis Laferrière <alexis.laf@xymus.net>
Thu, 12 Apr 2012 19:38:17 +0000 (15:38 -0400)
Signed-off-by: Alexis Laferrière <alexis.laf@xymus.net>

lib/standard/file.nit
lib/standard/file_nit.c
lib/standard/file_nit.h

index 00fbb32..7a67c26 100644 (file)
@@ -286,6 +286,9 @@ redef class String
                        return null
                end
        end
+
+       # returns files contained within the directory represented by self
+       fun files : Set[ String ] is extern import HashSet, HashSet::add, String::from_cstring, String::to_cstring, HashSet[String] as( Set[String] ), String as( Object )
 end
 
 redef class NativeString
index f9c5654..02b725e 100644 (file)
 #include <unistd.h>
 #include <sys/types.h>
 #include <string.h>
+#include <dirent.h>
+
+#include "file_nit.h"
+
+
+/*
+C implementation of file::String::files
+
+Imported methods signatures:
+       HashSet new_HashSet(  ) for hash_collection::HashSet::init
+       void HashSet_add( HashSet recv, Object item ) for hash_collection::HashSet::(abstract_collection::SimpleCollection::add)
+       String new_String_from_cstring( char * str ) for string::String::from_cstring
+       int HashSet_is_a_Set( HashSet value ) to check if a HashSet[String] is a Set[String]
+       Set HashSet_as_Set( HashSet value ) to cast from HashSet[String] to Set[String]
+*/
+Set String_files___impl( String recv )
+{
+       char *dir_path;
+       DIR *dir;
+
+       dir_path = String_to_cstring( recv );
+       if ((dir = opendir(dir_path)) == NULL)
+       {
+               perror( dir_path );
+               exit( 1 );
+       }
+       else
+       {
+               HashSet results;
+               String file_name;
+               struct dirent *de;
+
+               results = new_HashSet();
+
+               while ( ( de = readdir( dir ) ) != NULL )
+                       if ( strcmp( de->d_name, ".." ) != 0 &&
+                               strcmp( de->d_name, "." ) != 0 )
+                       {
+                               file_name = new_String_from_cstring( strdup( de->d_name ) );
+                               HashSet_add( results, String_as_Object( file_name ) );
+                       }
+
+               closedir( dir );
+               return HashSet_as_Set( results );
+       }
+}
 
 int string_NativeString_NativeString_file_exists_0(char *f){
        FILE *hdl = fopen(f,"r");
index de67757..9fba428 100644 (file)
 #include <stdio.h>
 #include <sys/types.h>
 
+#include <file._nitni.h>
+
+Set String_files___impl( String recv );
+
 extern int string_NativeString_NativeString_file_exists_0(char *f);
 extern void *string_NativeString_NativeString_file_stat_0(char *f);
 extern void *file_NativeFile_NativeFile_file_stat_0(FILE *f);