preliminary code. Segfaults.
[libeditor.git] / editor / editor.c
blobfc38dd89590de8c3dd7a0018a3dc6342889777f7
1 #include "editor.h"
2 #include <stdlib.h> // malloc(), free()
4 File *filebuffers = NULL;
5 uint64_t numbuffers = 0;
7 // returns an index
8 // we don't read 1 char at a time, because then we would have to either reallocate each line again for each character read or allocate a huge buffer
9 int readfile(char *fn) {
10 filebuffers = malloc(sizeof(File) * 5);
11 File tmp;
12 uint64_t numlines = 0, linechars = 0, filechars, i, index; // Unfortunately, this does not work on files of more than 18446744073709551616 bytes
13 int64_t line = 0;
14 uint32_t *linelengths;
15 uint32_t linelength;
16 char *buf;
17 char ch;
19 tmp.fn = fn;
20 tmp.fp = fopen(tmp.fn, "r");
22 if (tmp.fp == NULL) {
23 fclose(tmp.fp);
24 return -1;
27 // definitely open
29 // Credit to http://stackoverflow.com/a/3464656
30 fseek(tmp.fp, 0, SEEK_END);
31 filechars = ftell(tmp.fp);
32 rewind(tmp.fp);
34 buf = malloc(sizeof(char) * filechars);
36 fread(buf, sizeof(char), filechars, tmp.fp);
38 // count the newlines
39 for (i = 0; i < filechars; ch = buf[i++]) {
40 if (ch == '\n') {
41 numlines++;
44 tmp.text = malloc(sizeof(char*) * numlines);
45 linelengths = malloc(sizeof(uint64_t) * numlines);
47 tmp.numlines = numlines;
49 // count the number of chars in each line
50 for (i = 0; i < filechars; ch = buf[i++]) {
51 if (ch == '\n') {
52 linelengths[line] = linelength;
53 linelength = 0;
54 line++;
55 } else {
56 linelength++;
60 for (i = 0; i < numlines+1; i++) {
61 tmp.text[i] = malloc(sizeof(char) * (linelengths[1] + 2));
64 line = -1;
66 // actually read the lines out
67 for (i = 0; i < filechars; ch = buf[i++]) {
68 if (ch == '\n') {
69 (tmp.text[line])[index] = '\0';
70 index = 0;
71 line++;
72 } else {
73 (tmp.text[line])[index] = ch;
74 index++;
80 void closebuffer(int index) {
81 if ((index >= numbuffers) || (numbuffers == 0)) {
82 return;
85 if (!(filebuffers[index].isclosed)) {
86 fclose(filebuffers[index].fp);
89 File *files = malloc(sizeof(File)*(numbuffers-1));
91 if (index != 0) {for (int i=0; i < index; i++) {
92 files[i] = filebuffers[i];
95 if (index != numbuffers-1) { for (int i=index+1; i < numbuffers-1; i++) {
96 files[i-1] = filebuffers[i];
99 free(filebuffers);
100 filebuffers = files;
101 numbuffers--;
105 void closeallbuffers() {
106 while (numbuffers) {
107 closebuffer(0);