medium sized dollop
[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 = malloc( fsize + reserve_end );
29
30 if( buf )
31 {
32 /* Invalid / corrupt read */
33 if( fread( buf, 1, fsize, f ) != fsize )
34 {
35 free( buf );
36 buf = NULL;
37 }
38 }
39
40 *size = fsize;
41
42 fclose( f );
43 return buf;
44 }
45 else
46 {
47 return NULL;
48 }
49 }
50
51 static char *vg_disk_load_text( const char *path, i64 *size )
52 {
53 char *buf;
54 i64 fsize;
55
56 if( (buf = (char *)vg_disk_open_read( path, 1, &fsize )) )
57 {
58 buf[ fsize ] = 0x00;
59 *size = fsize +1;
60
61 return buf;
62 }
63
64 return NULL;
65 }
66
67 static void *vg_asset_read_s( const char *path, i64 *size )
68 {
69 return vg_disk_open_read( path, 0, size );
70 }
71
72 static void *vg_asset_read( const char *path )
73 {
74 i64 size;
75 return vg_disk_open_read( path, 0, &size );
76 }
77
78 static char *vg_textasset_read_s( const char *path, i64 *size )
79 {
80 return vg_disk_load_text( path, size );
81 }
82
83 static char *vg_textasset_read( const char *name )
84 {
85 i64 size;
86 return vg_disk_load_text( name, &size );
87 }
88
89 static int vg_asset_write( const char *path, void *data, i64 size )
90 {
91 FILE *f = fopen( path, "wb" );
92 if( f )
93 {
94 fwrite( data, size, 1, f );
95 fclose( f );
96 return 1;
97 }
98 else
99 {
100 return 0;
101 }
102 }
103
104 #endif /* VG_IO_H */