02b725e2d461fe4125f6481ff3fa1d5f37d9f210
[nit.git] / c_src / file_nit.c
1 /* This file is part of NIT ( http://www.nitlanguage.org ).
2 *
3 * Copyright 2004-2008 Jean Privat <jean@pryen.org>
4 * Copyright 2008 Floréal Morandat <morandat@lirmm.fr>
5 * Copyright 2008 Jean-Sébastien Gélinas <calestar@gmail.com>
6 *
7 * This file is free software, which comes along with NIT. This software is
8 * distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY;
9 * without even the implied warranty of MERCHANTABILITY or FITNESS FOR A
10 * PARTICULAR PURPOSE. You can modify it is you want, provided this header
11 * is kept unaltered, and a notification of the changes is added.
12 * You are allowed to redistribute it and sell it, alone or is a part of
13 * another product.
14 */
15
16 #include <stdlib.h>
17 #include <stdio.h>
18 #include <sys/stat.h>
19 #include <unistd.h>
20 #include <sys/types.h>
21 #include <string.h>
22 #include <dirent.h>
23
24 #include "file_nit.h"
25
26
27 /*
28 C implementation of file::String::files
29
30 Imported methods signatures:
31 HashSet new_HashSet( ) for hash_collection::HashSet::init
32 void HashSet_add( HashSet recv, Object item ) for hash_collection::HashSet::(abstract_collection::SimpleCollection::add)
33 String new_String_from_cstring( char * str ) for string::String::from_cstring
34 int HashSet_is_a_Set( HashSet value ) to check if a HashSet[String] is a Set[String]
35 Set HashSet_as_Set( HashSet value ) to cast from HashSet[String] to Set[String]
36 */
37 Set String_files___impl( String recv )
38 {
39 char *dir_path;
40 DIR *dir;
41
42 dir_path = String_to_cstring( recv );
43 if ((dir = opendir(dir_path)) == NULL)
44 {
45 perror( dir_path );
46 exit( 1 );
47 }
48 else
49 {
50 HashSet results;
51 String file_name;
52 struct dirent *de;
53
54 results = new_HashSet();
55
56 while ( ( de = readdir( dir ) ) != NULL )
57 if ( strcmp( de->d_name, ".." ) != 0 &&
58 strcmp( de->d_name, "." ) != 0 )
59 {
60 file_name = new_String_from_cstring( strdup( de->d_name ) );
61 HashSet_add( results, String_as_Object( file_name ) );
62 }
63
64 closedir( dir );
65 return HashSet_as_Set( results );
66 }
67 }
68
69 int string_NativeString_NativeString_file_exists_0(char *f){
70 FILE *hdl = fopen(f,"r");
71 if(hdl != NULL){
72 fclose(hdl);
73 }
74 return hdl != NULL;
75 }
76
77 void *to_nit_file_stat(struct stat* st){
78 struct stat* stat_element;
79 stat_element = malloc(sizeof(struct stat));
80 return memcpy(stat_element, st, sizeof(struct stat));
81 }
82
83 void *string_NativeString_NativeString_file_stat_0(char *f){
84 struct stat buff;
85 if(stat(f, &buff) != -1)
86 return to_nit_file_stat(&buff);
87 return 0;
88 }
89
90 void *file_NativeFile_NativeFile_file_stat_0(FILE *f){
91 struct stat buff;
92 if(fstat(fileno(f), &buff) != -1)
93 return to_nit_file_stat(&buff);
94 return 0;
95 }
96
97 extern int string_NativeString_NativeString_file_delete_0(char *f){
98 return (remove(f) == 0);
99 }