summaryrefslogtreecommitdiff
path: root/minilib/io.c
blob: 4c56c021a225591f0a34365ed9c6cfbef563eec2 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
#include "io.h"
#include "minilib.h"
#include "arena.h"
#include "string.h"

/* TODO: this is the Linux hosted environment */
#define _GNU_SOURCE
#include <unistd.h>
#include <sys/syscall.h>

#include <stdio.h>

void print( char *s )
{
	syscall( __NR_write, STDOUT_FILENO, s, strlen( s ) );
	syscall( __NR_write, STDOUT_FILENO, "\n", 1 );
}

int readfile( char *filename, char *s, int size )
{
	/* TODO: this is host-only */
	FILE *f = fopen( filename, "rb" );
	
	if( !f ) {
		return -1;
	}
	
	fread( s, size, 1, f );
	
	fclose( f );
	
	return 0;
}

int writefile( char *filename, char *s, int size )
{
	/* TODO: this is host-only */
	FILE *f = fopen( filename, "wb" );
	
	if( !f ) {
		return -1;
	}
	
	fwrite( s, size, 1, f );
	
	fclose( f );
	
	return 0;
}

char *readallfile( char *filename )
{
	/* TODO: this is host-only */
	FILE *f = fopen( filename, "rb" );
	int size;
	char *buf;
	
	if( !f ) {
		return NULL;
	}
	
	fseek( f, 0, SEEK_END );
	size = ftell( f );
	rewind( f );
	
	
	buf = allocate( size + 1 );

	if( size == 0 ) {
		buf[size] = '\0';
		fclose( f );
		return buf;
	}
	
	if( fread( buf, size, 1, f ) != 1 ) {
		return NULL;
	}
	
	buf[size] = '\0';
	
	fclose( f );
	
	return buf;
}