From f8b92ce3aa08b1445c9f956d8166830946562d12 Mon Sep 17 00:00:00 2001 From: navewindre Date: Wed, 3 Sep 2025 20:10:09 +0200 Subject: a --- src/util/file.h | 78 +++++++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 78 insertions(+) create mode 100644 src/util/file.h (limited to 'src/util/file.h') diff --git a/src/util/file.h b/src/util/file.h new file mode 100644 index 0000000..e19a390 --- /dev/null +++ b/src/util/file.h @@ -0,0 +1,78 @@ +#pragma once + +#include +#include +#include +#include +#include +#include "typedef.h" +#include "allocator.h" + +inline void* file_read( const char* file ) { + FILE* f = fopen( file, "rb" ); + if( !f ) + return 0; + + defer( fclose( f ) ); + + fseek( f, 0, SEEK_END ); + U64 size = ftell( f ); + rewind( f ); + if( !size ) + return 0; + + void* block = malloc( size + 1 ); + fread( block, size, 1, f ); + + ( (U8*)block )[size] = 0; + return block; +} + +inline void file_write( const char* file, U8* data, U32 size ) { + FILE* f = fopen( file, "wb" ); + if( !f ) + return; + + fwrite( data, size, 1, f ); + fclose( f ); +} + +inline const char* file_path_last_of( const char* path ) { + const char* last_slash = strrchr( path, '/' ); + return last_slash? last_slash + 1 : path; +} + +struct FILE_ENTRY { + char name[256]; + U8 dir; +}; + +inline LIST dir_get_entries( const char* path ) { + LIST entries; + + DIR* dir = opendir( path ); + if( !dir ) + return entries; + + struct dirent* entry; + struct stat file_stat; + char full_path[512]; + + while( !!( entry = readdir( dir ) ) ) { + if( !strcmp( entry->d_name, "." ) || !strcmp( entry->d_name, ".." ) ) + continue; + + snprintf( full_path, sizeof(full_path), "%s/%s", path, entry->d_name); + if( stat( full_path, &file_stat ) ) + continue; + + FILE_ENTRY file_entry; + strncpy( file_entry.name, entry->d_name, sizeof(file_entry.name) - 1 ); + file_entry.name[sizeof(file_entry.name) - 1] = '\0'; + file_entry.dir = S_ISDIR( file_stat.st_mode ) ? 1 : 0; + entries.push( file_entry ); + } + + closedir( dir ); + return entries; +} -- cgit v1.2.3