added open commmand

master
bx 2022-04-02 12:46:20 +00:00
parent 39ab7a9055
commit 7e684b606d
7 changed files with 56 additions and 8 deletions

10
b_truncate.c 100644
View File

@ -0,0 +1,10 @@
void
b_truncate(Row *row) {
Row *n = row->n;
row->n = NULL;
if (n != NULL) {
b_truncate(n);
free(n);
}
}

24
c_open.c 100644
View File

@ -0,0 +1,24 @@
void
c_open(char *file) {
file += 2;
FILE *f = fopen(file, "r");
if (f == NULL) {
puts("couldnt open file.");
return;
}
b_truncate(buffer);
Row *row = buffer;
row->n = NULL;
while (1) {
size_t red = fread(&row->text, 1, ROW_SIZE, f);
if (red < ROW_SIZE) {
break;
} else {
Row *new_row = calloc(1, sizeof(Row));
new_row->p = row;
row->n = new_row;
row = new_row;
}
}
}

View File

@ -1,3 +1,4 @@
void (*commands[256])(char *) = { void (*commands[256])(char *) = {
NULL, NULL,
['q'] = c_quit, ['q'] = c_quit,
['O'] = c_open,

2
efn.c
View File

@ -12,4 +12,6 @@
}; };
#include "c_quit.c" #include "c_quit.c"
#include "c_open.c"
#include "b_truncate.c"

3
efn.h
View File

@ -5,3 +5,6 @@ extern void (*commands[256])(char *);
void c_quit(char *); void c_quit(char *);
void c_open(char *);
#include <string.h>
void b_truncate(Row *);

View File

@ -0,0 +1,3 @@
Row init_row = { 0 };
Row *buffer = &init_row;

7
main.c
View File

@ -2,7 +2,11 @@ int
main(int argc, char **argv) { main(int argc, char **argv) {
static char buf[256]; static char buf[256];
while(1) { while(1) {
char *com = fgets(buf, sizeof(buf), stdin); memset(buf, 0, sizeof(buf));
char *com = fgets(buf, sizeof(buf), stdin);
for (int i = 0; i < sizeof(buf); i++)
if (buf[i] == '\n')
buf[i] = '\0';
if (com != NULL) { if (com != NULL) {
if (commands[com[0]] != NULL) commands[com[0]](buf); if (commands[com[0]] != NULL) commands[com[0]](buf);
else puts("invalid command."); else puts("invalid command.");
@ -10,3 +14,4 @@ main(int argc, char **argv) {
} }
return 0; return 0;
} }