Line data Source code
1 : // System Includes
2 : #include <stdio.h> // fopen, fclose, fseek, ftell, fread
3 :
4 : // Internal Includes
5 : #include "kirke/allocator.h"
6 : #include "kirke/error.h"
7 : #include "kirke/io.h"
8 : #include "kirke/string.h"
9 :
10 2 : String* io__read_text_file( Allocator* allocator, String* file_path, Error* error ){
11 2 : FILE* input_file = fopen( file_path->data, "r" );
12 :
13 2 : if( input_file == NULL ){
14 1 : error__set(
15 : error,
16 : "IO",
17 : IO__Error__UnableToOpenFile,
18 : "Unable to open input file \"%s.\"", file_path->data
19 : );
20 :
21 1 : return NULL;
22 : }
23 :
24 : unsigned long long input_file_size;
25 1 : fseek( input_file, 0, SEEK_END );
26 1 : input_file_size = ftell( input_file );
27 :
28 1 : String* output = allocator__alloc( allocator, sizeof( String ) );
29 1 : string__initialize( output, allocator, input_file_size );
30 :
31 1 : fseek( input_file, 0, SEEK_SET );
32 1 : output->length = fread( output->data, 1, input_file_size, input_file );
33 :
34 1 : fclose( input_file );
35 :
36 1 : return output;
37 : }
38 :
39 0 : String* io__read_stdin( Allocator* allocator ){
40 0 : String* output = allocator__alloc( allocator, sizeof( String ) );
41 0 : string__initialize( output, allocator, 0 );
42 :
43 0 : AutoString auto_string = {
44 : .string = output,
45 : .allocator = allocator
46 : };
47 :
48 : char buffer[ 1024 ];
49 : long bytes_read;
50 0 : while( ( bytes_read = fread( buffer, sizeof( char ), sizeof( buffer ), stdin ) ) > 0 ){
51 0 : auto_string__append_elements( &auto_string, bytes_read, buffer );
52 : }
53 :
54 0 : return output;
55 : }
|