-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathbuf.c
90 lines (83 loc) · 1.54 KB
/
buf.c
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
85
86
87
88
89
90
#include <u.h>
#include <libc.h>
#include <draw.h>
#include <mouse.h>
#include <keyboard.h>
#include "a.h"
int
readfile(Buffer *buf, char *filename)
{
int fd;
long r;
buf->count = 0;
buf->size = 8192;
buf->data = malloc(buf->size);
if(buf->data == nil)
return -1;
fd = open(filename, OREAD);
if(fd < 0)
return -1;
for(;;){
r = read(fd, buf->data + buf->count, buf->size - buf->count);
if(r < 0)
return -1;
if(r == 0)
break;
buf->count += r;
if(buf->count == buf->size){
buf->size *= 1.5;
buf->data = realloc(buf->data, buf->size);
if(buf->data == nil)
return -1;
}
}
buf->data[buf->count] = 0;
close(fd);
return 0;
}
int
writefile(Buffer *buf, char *filename)
{
int fd, n;
fd = open(filename, OWRITE|OTRUNC);
if(fd < 0)
return -1;
n = write(fd, buf->data, buf->count);
if(n < 0 || n != buf->count)
return -1;
close(fd);
return 0;
}
int
delete(Buffer *buf, int index)
{
if(index != buf->count - 1)
memmove(&buf->data[index], &buf->data[index + 1], buf->count - index);
buf->count -= 1;
/* TODO: is that really what we want ? */
if(buf->count == 0){
buf->count = 1;
buf->data[0] = 0;
}
return 0;
}
int
insert(Buffer *buf, int index)
{
if(buf->count == buf->size){
buf->size *= 1.5;
buf->data = realloc(buf->data, buf->size);
if(buf->data == nil)
return -1;
}
buf->count += 1;
memmove(&buf->data[index + 1], &buf->data[index], buf->count - index);
buf->data[index] = 0;
buf->data[buf->count] = 0;
return 1;
}
int
append(Buffer *buf, int index)
{
return insert(buf, index + 1);
}