init
[csRadar.git] / csrIO.h
1 // Low level disk reading
2 //=======================================================================================================================
3
4 i64 fs_file_size( FILE *fileptr )
5 {
6 fseek( fileptr, 0, SEEK_END );
7 i64 fsize = ftell( fileptr );
8 fseek( fileptr, 0, SEEK_SET );
9
10 return fsize;
11 }
12
13 void *fs_disk_open_read( const char *path, int const reserve_end, i64 *size )
14 {
15 FILE *f = fopen( path, "rb" );
16 if( f )
17 {
18 i64 fsize = fs_file_size( f );
19 void *buf = csr_malloc( fsize + reserve_end );
20
21 if( buf )
22 {
23 // Invalid / corrupt read
24 if( fread( buf, 1, fsize, f ) != fsize )
25 {
26 free( buf );
27 buf = NULL;
28 }
29 }
30
31 *size = fsize;
32
33 fclose( f );
34 return buf;
35 }
36 else
37 {
38 return NULL;
39 }
40 }
41
42 char *fs_disk_load_text( const char *path, i64 *size )
43 {
44 char *buf;
45 i64 fsize;
46
47 if( (buf = fs_disk_open_read( path, 1, &fsize )) )
48 {
49 buf[ fsize ] = 0x00;
50 *size = fsize +1;
51
52 return buf;
53 }
54
55 return NULL;
56 }
57
58 void *csr_asset_read_s( const char *path, i64 *size )
59 {
60 return fs_disk_open_read( path, 0, size );
61 }
62
63 void *csr_asset_read( const char *path )
64 {
65 i64 size;
66 return fs_disk_open_read( path, 0, &size );
67 }
68
69 char *csr_textasset_read_s( const char *path, i64 *size )
70 {
71 return fs_disk_load_text( path, size );
72 }
73
74 char *csr_textasset_read( const char *name )
75 {
76 i64 size;
77 return fs_disk_load_text( name, &size );
78 }
79
80 // Find file path extension, returns NULL if no ext (0x00)
81 char *csr_findext( char *path, char const delim )
82 {
83 char *c, *ptr;
84
85 c = path;
86 ptr = NULL;
87
88 while( *c )
89 {
90 if( *c == delim )
91 {
92 ptr = c + 1;
93 }
94
95 c ++;
96 }
97
98 return ptr;
99 }
100
101 // gets rid of extension on string only left with folder/filename
102 void csr_stripext( char *path )
103 {
104 char *point, *start;
105
106 // Skip folders
107 if( !(start = csr_findext( path, '/' )) )
108 {
109 start = path;
110 }
111
112 if( (point = csr_findext( start, '.' )) )
113 {
114 if( point > path )
115 {
116 *(point-1) = 0x00;
117 }
118 }
119 }
120
121 // Convert windows paths to unix-ish ( \something\\blahblah .. ) -> /something/blahblah/
122 void csr_path_winunix( char *path )
123 {
124 char *idx, *wr;
125 wr = idx = path;
126
127 while( *idx )
128 {
129 if( *idx == '\\' )
130 {
131 *idx = '/';
132 }
133
134 if( idx > path )
135 {
136 if( *(idx -1) == '/' && *idx == '/') idx ++;
137 }
138
139 *( wr ++ ) = *idx;
140
141 idx ++;
142 }
143
144 *wr = 0x00;
145 }
146
147 int csr_path_is_abs( char const *path )
148 {
149 #ifdef _WIN32
150 if( strlen( path ) < 2 ) return 0;
151 return path[1] == ':';
152 #else
153 if( strlen( path ) < 1 ) return 0;
154 return path[0] == '/';
155 #endif
156 }
157
158 #ifdef _WIN32
159 #define GetWorkingDir _getcwd
160 #else
161 #define GetWorkingDir getcwd
162 #endif