switch to async system
[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 void *buffer = vg_linear_alloc( lin_alloc, 0 );
41 u64 current = 0;
42
43 /* read in chunks */
44 for( u32 i=0; 1; i++ ){
45 buffer = vg_linear_extend( lin_alloc, buffer, VG_FILE_IO_CHUNK_SIZE );
46
47 u64 l = fread( buffer + current, 1, VG_FILE_IO_CHUNK_SIZE, f );
48 current += l;
49
50 if( l != VG_FILE_IO_CHUNK_SIZE ){
51 if( feof( f ) ){
52 break;
53 }
54 else{
55 if( ferror( f ) ){
56 fclose(f);
57 vg_fatal_error( "read error" );
58 }
59 else{
60 fclose(f);
61 vg_fatal_error( "unknown error codition" );
62 }
63 }
64 }
65 }
66
67 buffer = vg_linear_resize( lin_alloc, buffer, vg_align8(current) );
68 fclose( f );
69
70 *size = (u32)current;
71
72 return buffer;
73 }
74 else
75 {
76 vg_error( "vg_disk_open_read: %s\n", strerror(errno) );
77 return NULL;
78 }
79 }
80
81 /* read entire file and append a null on the end */
82 VG_STATIC char *vg_file_read_text( void *lin_alloc, const char *path, u32 *sz )
83 {
84 u32 size;
85 char *str = vg_file_read( lin_alloc, path, &size );
86
87 if( !str )
88 return NULL;
89
90 /* include null terminator */
91 str = vg_linear_extend( lin_alloc, str, 1 );
92 str[ size ] = '\0';
93 *sz = size+1;
94
95 return str;
96 }
97
98
99 VG_STATIC int vg_asset_write( const char *path, void *data, i64 size )
100 {
101 FILE *f = fopen( path, "wb" );
102 if( f )
103 {
104 fwrite( data, size, 1, f );
105 fclose( f );
106 return 1;
107 }
108 else
109 {
110 return 0;
111 }
112 }
113
114 #endif /* VG_IO_H */