way better controller handling
[vg.git] / vg_io.h
1 /* Copyright (C) 2021-2022 Harry Godden (hgn) - All Rights Reserved */
2
3 #ifndef VG_IO_H
4 #define VG_IO_H
5
6 #include "vg_stdint.h"
7 #include "vg_platform.h"
8 #include "vg_log.h"
9 #include "vg_mem.h"
10 #include <stdio.h>
11 #include <errno.h>
12
13 #define _TINYDIR_MALLOC(_size) vg_linear_alloc( vg_mem.scratch, _size )
14 #define _TINYDIR_FREE(_size)
15
16 #include "submodules/tinydir/tinydir.h"
17
18 /*
19 * File I/O
20 */
21
22 #define VG_FILE_IO_CHUNK_SIZE 1024*256
23
24 VG_STATIC void vg_file_print_invalid( FILE *fp )
25 {
26 if( feof( fp )) {
27 vg_error( "mdl_open: header too short\n" );
28 }
29 else{
30 if( ferror( fp ))
31 vg_error( "mdl_open: %s\n", strerror(errno) );
32 else
33 vg_error( "mdl_open: unkown failure\n" );
34
35 }
36 }
37
38 /* read entire binary file */
39 VG_STATIC void *vg_file_read( void *lin_alloc, const char *path, u32 *size )
40 {
41 FILE *f = fopen( path, "rb" );
42 if( f ){
43 void *buffer = vg_linear_alloc( lin_alloc, 0 );
44 u64 current = 0;
45
46 /* read in chunks */
47 for( u32 i=0; 1; i++ ){
48 buffer = vg_linear_extend( lin_alloc, buffer, VG_FILE_IO_CHUNK_SIZE );
49
50 u64 l = fread( buffer + current, 1, VG_FILE_IO_CHUNK_SIZE, f );
51 current += l;
52
53 if( l != VG_FILE_IO_CHUNK_SIZE ){
54 if( feof( f ) ){
55 break;
56 }
57 else{
58 if( ferror( f ) ){
59 fclose(f);
60 vg_fatal_error( "read error" );
61 }
62 else{
63 fclose(f);
64 vg_fatal_error( "unknown error codition" );
65 }
66 }
67 }
68 }
69
70 buffer = vg_linear_resize( lin_alloc, buffer, vg_align8(current) );
71 fclose( f );
72
73 *size = (u32)current;
74
75 return buffer;
76 }
77 else{
78 vg_error( "vg_disk_open_read: %s\n", strerror(errno) );
79 return NULL;
80 }
81 }
82
83 /* read entire file and append a null on the end */
84 VG_STATIC char *vg_file_read_text( void *lin_alloc, const char *path, u32 *sz )
85 {
86 u32 size;
87 char *str = vg_file_read( lin_alloc, path, &size );
88
89 if( !str )
90 return NULL;
91
92 /* include null terminator */
93 str = vg_linear_extend( lin_alloc, str, 1 );
94 str[ size ] = '\0';
95 *sz = size+1;
96
97 return str;
98 }
99
100
101 VG_STATIC int vg_asset_write( const char *path, void *data, i64 size ){
102 FILE *f = fopen( path, "wb" );
103 if( f ){
104 fwrite( data, size, 1, f );
105 fclose( f );
106 return 1;
107 }
108 else{
109 return 0;
110 }
111 }
112
113 #endif /* VG_IO_H */