fmt: ignore signs if preceded by a non-space
[ctxt.git] / txt.c
blobd2dcb38aa27e6be908e24287da82c6a1c31e43a8
1 #include <stdlib.h>
2 #include <string.h>
3 #include <unistd.h>
4 #include "ctxt.h"
5 #include "util.h"
7 static char *file_read(int fd)
9 int size = 1024;
10 char *buf = xmalloc(size);
11 int n = 0;
12 int c = 0;
13 while ((c = read(fd, buf + n, size - n)) > 0) {
14 n += c;
15 if (n == size) {
16 char *newbuf = xmalloc(size * 2);
17 memcpy(newbuf, buf, n);
18 size *= 2;
21 return buf;
24 static int newlines(char *s)
26 int i;
27 for (i = 0; (s = strchr(s, '\n')); i++, s++);
28 return i;
31 static void initlines(struct txt *txt)
33 int i;
34 txt->lines[0] = txt->txt;
35 for (i = 1; i <= txt->n; i++) {
36 char *s = strchr(txt->lines[i - 1], '\n');
37 if (s)
38 *s = '\0';
39 if (i < txt->n)
40 txt->lines[i] = s + 1;
44 struct txt *txt_alloc(int fd)
46 struct txt *txt = xmalloc(sizeof(struct txt));
47 txt->txt = file_read(fd);
48 txt->n = newlines(txt->txt);
49 txt->lines = xmalloc(sizeof(*txt->lines) * txt->n);
50 initlines(txt);
51 return txt;
54 char *txt_line(struct txt *txt, int line)
56 if (line < txt->n)
57 return txt->lines[line];
58 return NULL;
61 void txt_free(struct txt *txt)
63 free(txt->lines);
64 free(txt->txt);