Refactor, GLFW->SDL
[vg.git] / vg_io.h
diff --git a/vg_io.h b/vg_io.h
new file mode 100644 (file)
index 0000000..d962bc4
--- /dev/null
+++ b/vg_io.h
@@ -0,0 +1,121 @@
+/* Copyright (C) 2021-2022 Harry Godden (hgn) - All Rights Reserved */
+
+#ifndef VG_IO_H
+#define VG_IO_H
+
+#include "vg_stdint.h"
+#include "vg_platform.h"
+#include "vg_log.h"
+#include "vg_mem.h"
+#include <stdio.h>
+#include <errno.h>
+
+/*
+ * File I/O
+ */
+
+#define VG_FILE_IO_CHUNK_SIZE 1024*256
+
+VG_STATIC void vg_file_print_invalid( FILE *fp )
+{
+   if( feof( fp )) 
+   {
+      vg_error( "mdl_open: header too short\n" );
+   }
+   else
+   {
+      if( ferror( fp ))
+         vg_error( "mdl_open: %s\n", strerror(errno) );
+      else
+         vg_error( "mdl_open: unkown failure\n" );
+
+   }
+}
+
+/* read entire binary file */
+VG_STATIC void *vg_file_read( void *lin_alloc, const char *path, u32 *size )
+{
+       FILE *f = fopen( path, "rb" );
+       if( f )
+       {
+      void *buffer = vg_linear_alloc( lin_alloc, 0 );
+      u64 current = 0;
+
+      /* read in chunks */
+      for( u32 i=0; 1; i++ )
+      {
+         buffer = vg_linear_extend( lin_alloc, buffer, VG_FILE_IO_CHUNK_SIZE );
+
+         u64 l = fread( buffer + current, 1, VG_FILE_IO_CHUNK_SIZE, f );
+         current += l;
+
+         if( l != VG_FILE_IO_CHUNK_SIZE )
+         {
+            if( feof( f ) )
+            {
+               break;
+            }
+            else
+            {
+               if( ferror( f ) )
+               {
+                  fclose(f);
+                  vg_fatal_exit_loop( "read error" );
+               }
+               else
+               {
+                  fclose(f);
+                  vg_fatal_exit_loop( "unknown error codition" );
+               }
+            }
+         }
+      }
+
+      buffer = vg_linear_resize( lin_alloc, buffer, current );
+               fclose( f );
+
+      *size = (u32)current;
+      
+      return buffer;
+       }
+       else
+       {
+      vg_error( "vg_disk_open_read: %s\n", strerror(errno) );
+               return NULL;
+       }
+}
+
+/* read entire file and append a null on the end */
+VG_STATIC char *vg_file_read_text( void *lin_alloc, const char *path, u32 *sz )
+{
+   u32 size;
+   char *str = vg_file_read( lin_alloc, path, &size );
+
+   if( !str )
+      return NULL;
+
+   /* include null terminator */
+   str = vg_linear_extend( lin_alloc, str, 1 );
+   str[ size ] = '\0';
+   *sz = size+1;
+
+   return str;
+}
+
+
+VG_STATIC int vg_asset_write( const char *path, void *data, i64 size )
+{
+       FILE *f = fopen( path, "wb" );
+       if( f )
+       {
+               fwrite( data, size, 1, f );
+               fclose( f );
+               return 1;
+       }
+       else
+       {
+               return 0;
+       }
+}
+
+#endif /* VG_IO_H */