misc
[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 /*
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, u32 *size )
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 *size = (u32)current;
78
79 return buffer;
80 }
81 else
82 {
83 vg_error( "vg_disk_open_read: %s\n", strerror(errno) );
84 return NULL;
85 }
86 }
87
88 /* read entire file and append a null on the end */
89 VG_STATIC char *vg_file_read_text( void *lin_alloc, const char *path, u32 *sz )
90 {
91 u32 size;
92 char *str = vg_file_read( lin_alloc, path, &size );
93
94 if( !str )
95 return NULL;
96
97 /* include null terminator */
98 str = vg_linear_extend( lin_alloc, str, 1 );
99 str[ size ] = '\0';
100 *sz = size+1;
101
102 return str;
103 }
104
105
106 VG_STATIC int vg_asset_write( const char *path, void *data, i64 size )
107 {
108 FILE *f = fopen( path, "wb" );
109 if( f )
110 {
111 fwrite( data, size, 1, f );
112 fclose( f );
113 return 1;
114 }
115 else
116 {
117 return 0;
118 }
119 }
120
121 #endif /* VG_IO_H */