summaryrefslogtreecommitdiff
path: root/src/runtime/sys_file.c
blob: 1fc1e55e6501926377dd15a9129cf2ecc291ba88 (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
// Copyright 2009 The Go Authors.  All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.

#include "runtime.h"
#include "sys_types.h"

void
sys·readfile(string filein, string fileout, bool okout)
{
	int32 fd;
	byte namebuf[256];
	struct stat statbuf;

	fileout = nil;
	okout = false;

	if(filein == nil || filein->len >= sizeof(namebuf))
		goto out;

	mcpy(namebuf, filein->str, filein->len);
	namebuf[filein->len] = '\0';
	fd = open(namebuf, 0);
	if(fd < 0)
		goto out;

	if (fstat(fd, &statbuf) < 0)
		goto close_out;

	if (statbuf.st_size <= 0)
		goto close_out;

	fileout = mal(sizeof(fileout->len)+statbuf.st_size + 1);
	fileout->len = statbuf.st_size;

	if (read(fd, fileout->str, statbuf.st_size) != statbuf.st_size) {
		fileout = nil;
		goto close_out;
	}
	okout = true;

close_out:
	close(fd);
out:
	FLUSH(&fileout);
	FLUSH(&okout);
}

void
sys·writefile(string filein, string textin, bool okout)
{
	int32 fd;
	byte namebuf[256];

	okout = false;

	if(filein == nil || filein->len >= sizeof(namebuf))
		goto out;

	mcpy(namebuf, filein->str, filein->len);
	namebuf[filein->len] = '\0';
	fd = open(namebuf, 1|O_CREAT, 0644);  // open for write, create if non-existant (sic)
	if(fd < 0)
		goto out;

	if (write(fd, textin->str, textin->len) != textin->len) {
		goto close_out;
	}
	okout = true;

close_out:
	close(fd);
out:
	FLUSH(&okout);
}