Fix major overstep with last commit
[vg.git] / src / vg / 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 <stdio.h>
9
10 /*
11 * FIle I/O
12 */
13 static i64 vg_file_size( FILE *fileptr )
14 {
15 fseek( fileptr, 0, SEEK_END );
16 i64 fsize = ftell( fileptr );
17 fseek( fileptr, 0, SEEK_SET );
18
19 return fsize;
20 }
21
22 static void *vg_disk_open_read( const char *path, int reserve_end, i64 *size )
23 {
24 FILE *f = fopen( path, "rb" );
25 if( f )
26 {
27 i64 fsize = vg_file_size( f );
28 void *buf = vg_alloc( fsize + reserve_end );
29
30 /* Invalid / corrupt read */
31 if( fread( buf, 1, fsize, f ) != fsize )
32 {
33 vg_free( buf );
34 buf = NULL;
35 }
36
37 *size = fsize;
38
39 fclose( f );
40 return buf;
41 }
42 else
43 {
44 return NULL;
45 }
46 }
47
48 static char *vg_disk_load_text( const char *path, i64 *size )
49 {
50 char *buf;
51 i64 fsize;
52
53 if( (buf = (char *)vg_disk_open_read( path, 1, &fsize )) )
54 {
55 buf[ fsize ] = 0x00;
56 *size = fsize +1;
57
58 return buf;
59 }
60
61 return NULL;
62 }
63
64 static void *vg_asset_read_s( const char *path, i64 *size )
65 {
66 return vg_disk_open_read( path, 0, size );
67 }
68
69 static void *vg_asset_read( const char *path )
70 {
71 i64 size;
72 return vg_disk_open_read( path, 0, &size );
73 }
74
75 static char *vg_textasset_read_s( const char *path, i64 *size )
76 {
77 return vg_disk_load_text( path, size );
78 }
79
80 static char *vg_textasset_read( const char *name )
81 {
82 i64 size;
83 return vg_disk_load_text( name, &size );
84 }
85
86 static int vg_asset_write( const char *path, void *data, i64 size )
87 {
88 FILE *f = fopen( path, "wb" );
89 if( f )
90 {
91 fwrite( data, size, 1, f );
92 fclose( f );
93 return 1;
94 }
95 else
96 {
97 return 0;
98 }
99 }
100
101 #endif /* VG_IO_H */