Browse Source

Add an ability to create new files

rexim 4 years ago
parent
commit
cd56ad1511
3 changed files with 13 additions and 15 deletions
  1. 3 12
      editor.c
  2. 1 1
      editor.h
  3. 9 2
      main.c

+ 3 - 12
editor.c

@@ -186,22 +186,15 @@ void editor_save_to_file(const Editor *editor, const char *file_path)
     fclose(f);
 }
 
-void editor_load_from_file(Editor *editor, const char *file_path)
+void editor_load_from_file(Editor *editor, FILE *file)
 {
     assert(editor->lines == NULL && "You can only load files into an empty editor");
     editor_create_first_new_line(editor);
 
-    FILE *f = fopen(file_path, "r");
-    if (f == NULL) {
-        fprintf(stderr, "ERROR: could not open file `%s`: %s\n",
-                file_path, strerror(errno));
-        exit(1);
-    }
-
     static char chunk[640 * 1024];
 
-    while (!feof(f)) {
-        size_t n = fread(chunk, 1, sizeof(chunk), f);
+    while (!feof(file)) {
+        size_t n = fread(chunk, 1, sizeof(chunk), file);
 
         String_View chunk_sv = {
             .data = chunk,
@@ -222,6 +215,4 @@ void editor_load_from_file(Editor *editor, const char *file_path)
     }
 
     editor->cursor_row = 0;
-
-    fclose(f);
 }

+ 1 - 1
editor.h

@@ -25,7 +25,7 @@ typedef struct {
 } Editor;
 
 void editor_save_to_file(const Editor *editor, const char *file_path);
-void editor_load_from_file(Editor *editor, const char *file_path);
+void editor_load_from_file(Editor *editor, FILE *file);
 
 void editor_insert_text_before_cursor(Editor *editor, const char *text);
 void editor_insert_new_line(Editor *editor);

+ 9 - 2
main.c

@@ -174,7 +174,9 @@ void usage(FILE *stream)
     fprintf(stream, "Usage: te [FILE-PATH]\n");
 }
 
-// TODO: Save/Load file
+// TODO: Save file
+// TODO: ncurses renderer
+// TODO: scrolling
 // TODO: Jump forward/backward by a word
 // TODO: Delete a word
 // TODO: Blinking cursor
@@ -190,7 +192,11 @@ int main(int argc, char **argv)
     }
 
     if (file_path) {
-        editor_load_from_file(&editor, file_path);
+        FILE *file = fopen(file_path, "r");
+        if (file != NULL) {
+            editor_load_from_file(&editor, file);
+            fclose(file);
+        }
     }
 
     scc(SDL_Init(SDL_INIT_VIDEO));
@@ -292,3 +298,4 @@ int main(int argc, char **argv)
 
 #define SV_IMPLEMENTATION
 #include "./sv.h"
+