From e85314ba0ebf383d3c8a1cf2b527c1e12c206519 Mon Sep 17 00:00:00 2001 From: gunboy001 Date: Thu, 26 Dec 2019 23:06:45 +0100 Subject: [PATCH] can properly open empty and create files --- doc/useful links.txt | 7 ++++++- src/ste.c | 47 ++++++++++++++++++++++++++------------------ 2 files changed, 34 insertions(+), 20 deletions(-) diff --git a/doc/useful links.txt b/doc/useful links.txt index 80162dd..84b2d11 100644 --- a/doc/useful links.txt +++ b/doc/useful links.txt @@ -15,4 +15,9 @@ Write a simple text editor written in pure C: https://viewsourcecode.org/snaptoken/kilo/ All C keywords: - https://www.programiz.com/c-programming/list-all-keywords-c-language \ No newline at end of file + https://www.programiz.com/c-programming/list-all-keywords-c-language + +Nuklear: + https://github.com/Immediate-Mode-UI/Nuklear + https://github.com/vurtun/nuklear/wiki/Text-Edit + https://dexp.in/articles/nuklear-intro/ diff --git a/src/ste.c b/src/ste.c index db691a1..8d2d535 100644 --- a/src/ste.c +++ b/src/ste.c @@ -359,26 +359,35 @@ void drawBar (char *s) /* Open a file and put it into a buffer line by line */ void fileOpen (char *filename) { - FILE *fp = fopen(filename, "r"); - if (fp == NULL) die("Cannot open file", BAD_FILE); - - /* Init the linebuffer */ - char *line = NULL; - /* Set linecap to 0 so getline will atumatically allocate - * memory for the line buffer*/ - size_t linecap = 0; - ssize_t linelen; - - /* getline returns -1 if no new line is present */ - while ((linelen = getline(&line, &linecap, fp)) != -1) { - while (linelen > 0 && (line[linelen - 1] == '\n' || line[linelen - 1] == '\r')) - linelen--; - rowAddLast(&rows, line, linelen); + FILE *fd = fopen(filename, "a+"); + if (fd == NULL) die("Cannot open file", BAD_FILE); + + /* Check if the file is empty first */ + fseek (fd, 0, SEEK_END); + int size = ftell(fd); + if (size) { + rewind(fd); + + /* Init the linebuffer */ + char *line = NULL; + /* Set linecap to 0 so getline will atumatically allocate + * memory for the line buffer*/ + size_t linecap = 0; + ssize_t linelen; + + /* getline returns -1 if no new line is present */ + while ((linelen = getline(&line, &linecap, fd)) != -1) { + while (linelen > 0 && (line[linelen - 1] == '\n' || line[linelen - 1] == '\r')) + linelen--; + rowAddLast(&rows, line, linelen); + } + /* free the line buffer */ + free(line); + } else { + rowAddLast(&rows, " ", 1); } - /* free the line buffer */ - free(line); /* close the file */ - fclose(fp); + fclose(fd); } /*------------------------------------- file operations ----------------------------------*/ @@ -581,7 +590,7 @@ void updateInfo (void) getmaxyx(stdscr, t.dim.y, t.dim.x); t.dim.y -= 1; - t.pad = decimalSize(rows.rownum - 1); + t.pad = decimalSize(rows.rownum > 1 ? rows.rownum - 1 : 2); t.dim.x -= t.pad + 1; }