@@ -254,38 +254,45 @@ pm_string_file_init(pm_string_t *string, const char *filepath) {
254254 * string = (pm_string_t ) { .type = PM_STRING_OWNED , .source = source , .length = (size_t ) file_size };
255255 return PM_STRING_INIT_SUCCESS ;
256256#elif defined(PRISM_HAS_FILESYSTEM )
257- FILE * file = fopen (filepath , "rb" );
258- if (file == NULL ) {
257+ // Open the file for reading
258+ int fd = open (filepath , O_RDONLY );
259+ if (fd == -1 ) {
259260 return PM_STRING_INIT_ERROR_GENERIC ;
260261 }
261262
262- fseek (file , 0 , SEEK_END );
263- long file_size = ftell (file );
264-
265- if (file_size == -1 ) {
266- fclose (file );
263+ // Stat the file to get the file size
264+ struct stat sb ;
265+ if (fstat (fd , & sb ) == -1 ) {
266+ close (fd );
267267 return PM_STRING_INIT_ERROR_GENERIC ;
268268 }
269269
270- if (file_size == 0 ) {
271- fclose (file );
270+ // Ensure it is a file and not a directory
271+ if (S_ISDIR (sb .st_mode )) {
272+ close (fd );
273+ return PM_STRING_INIT_ERROR_DIRECTORY ;
274+ }
275+
276+ // Check the size to see if it's empty
277+ size_t size = (size_t ) sb .st_size ;
278+ if (size == 0 ) {
279+ close (fd );
272280 const uint8_t source [] = "" ;
273281 * string = (pm_string_t ) { .type = PM_STRING_CONSTANT , .source = source , .length = 0 };
274282 return PM_STRING_INIT_SUCCESS ;
275283 }
276284
277- size_t length = (size_t ) file_size ;
285+ size_t length = (size_t ) size ;
278286 uint8_t * source = xmalloc (length );
279287 if (source == NULL ) {
280- fclose ( file );
288+ close ( fd );
281289 return PM_STRING_INIT_ERROR_GENERIC ;
282290 }
283291
284- fseek (file , 0 , SEEK_SET );
285- size_t bytes_read = fread (source , length , 1 , file );
286- fclose (file );
292+ long bytes_read = (long ) read (fd , source , length );
293+ close (fd );
287294
288- if (bytes_read != 1 ) {
295+ if (bytes_read == - 1 ) {
289296 xfree (source );
290297 return PM_STRING_INIT_ERROR_GENERIC ;
291298 }
0 commit comments