c78930075c135fac28ec6565b95e1dcbdeda8b12
[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 "vg_log.h"
9 #include "vg_mem.h"
10 #include <stdio.h>
11 #include <errno.h>
12
13 /*
14 * File I/O
15 */
16
17 #define VG_FILE_IO_CHUNK_SIZE 1024*256
18
19 VG_STATIC void vg_file_print_invalid( FILE *fp )
20 {
21 if( feof( fp ))
22 {
23 vg_error( "mdl_open: header too short\n" );
24 }
25 else
26 {
27 if( ferror( fp ))
28 vg_error( "mdl_open: %s\n", strerror(errno) );
29 else
30 vg_error( "mdl_open: unkown failure\n" );
31
32 }
33 }
34
35 /* read entire binary file */
36 VG_STATIC void *vg_file_read( void *lin_alloc, const char *path )
37 {
38 FILE *f = fopen( path, "rb" );
39 if( f )
40 {
41 void *buffer = vg_linear_alloc( lin_alloc, 0 );
42 u64 current = 0;
43
44 /* read in chunks */
45 for( u32 i=0; 1; i++ )
46 {
47 buffer = vg_linear_extend( lin_alloc, buffer, VG_FILE_IO_CHUNK_SIZE );
48
49 u64 l = fread( buffer + current, 1, VG_FILE_IO_CHUNK_SIZE, f );
50 current += l;
51
52 if( l != VG_FILE_IO_CHUNK_SIZE )
53 {
54 if( feof( f ) )
55 {
56 break;
57 }
58 else
59 {
60 if( ferror( f ) )
61 {
62 fclose(f);
63 vg_fatal_exit_loop( "read error" );
64 }
65 else
66 {
67 fclose(f);
68 vg_fatal_exit_loop( "unknown error codition" );
69 }
70 }
71 }
72 }
73
74 buffer = vg_linear_resize( lin_alloc, buffer, current );
75 fclose( f );
76
77 return buffer;
78 }
79 else
80 {
81 vg_error( "vg_disk_open_read: %s\n", strerror(errno) );
82 return NULL;
83 }
84 }
85
86 /* get the size of the file just loaded */
87 VG_STATIC u32 vg_linear_last_size( void *allocator ); /* ? */
88 VG_STATIC u32 vg_file_size( void *lin_alloc )
89 {
90 return vg_linear_last_size( lin_alloc );
91 }
92
93 /* read entire file and append a null on the end */
94 VG_STATIC char *vg_file_read_text( void *lin_alloc, const char *path )
95 {
96 char *str = vg_file_read( lin_alloc, path );
97
98 if( !str )
99 return NULL;
100
101 /* include null terminator */
102 str = vg_linear_extend( lin_alloc, str, 1 );
103 str[ vg_file_size(lin_alloc) ] = '\0';
104
105 return str;
106 }
107
108
109 VG_STATIC int vg_asset_write( const char *path, void *data, i64 size )
110 {
111 FILE *f = fopen( path, "wb" );
112 if( f )
113 {
114 fwrite( data, size, 1, f );
115 fclose( f );
116 return 1;
117 }
118 else
119 {
120 return 0;
121 }
122 }
123
124 #endif /* VG_IO_H */