summaryrefslogtreecommitdiff
path: root/src/util/file.h
diff options
context:
space:
mode:
authornavewindre <boneyaard@gmail.com>2025-09-03 20:10:09 +0200
committernavewindre <boneyaard@gmail.com>2025-09-03 20:10:09 +0200
commitf8b92ce3aa08b1445c9f956d8166830946562d12 (patch)
tree94e63a5aec9f8f52b577f56799e0c9201fd976a5 /src/util/file.h
a
Diffstat (limited to 'src/util/file.h')
-rw-r--r--src/util/file.h78
1 files changed, 78 insertions, 0 deletions
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 <cstdlib>
+#include <cstring>
+#include <stdio.h>
+#include <dirent.h>
+#include <sys/stat.h>
+#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<FILE_ENTRY> dir_get_entries( const char* path ) {
+ LIST<FILE_ENTRY> 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;
+}