diff options
author | cflip <cflip@cflip.net> | 2023-01-16 14:14:25 -0700 |
---|---|---|
committer | cflip <cflip@cflip.net> | 2023-01-16 14:19:02 -0700 |
commit | 8be3915417bcafdbf2a8752980db96e06df096aa (patch) | |
tree | dc463de897bdc91220639809bef9082a7e5289a3 /file.c | |
parent | 58d38d02b215f2e4829ccdc399df8d59bb6cb140 (diff) |
Improve behaviour when opening a file from the command line
The editor had two issues when reading a file with a name from the
command line. The most annoying issue was that when reallocating the
internal filename in the editor, the null terminator wasn't copied which
sometimes left garbage at the end of the filename.
The other issue was that the editor would quit with a fatal error if
there was no file with the specified name, when it should open the file
anyway and just create it on save.
Diffstat (limited to 'file.c')
-rw-r--r-- | file.c | 11 |
1 files changed, 8 insertions, 3 deletions
@@ -37,15 +37,20 @@ char* editor_rows_to_string(struct editor_state* editor, int* buffer_length) void editor_open(struct editor_state* editor, char* filename) { free(editor->filename); - size_t filename_len = strlen(filename); + size_t filename_len = strlen(filename) + 1; editor->filename = malloc(filename_len); memcpy(editor->filename, filename, filename_len); editor_select_syntax_highlight(editor); + /* If there is no file with this name, the editor will create it on save. */ + if (access(filename, F_OK) != 0) + return; + FILE* fp = fopen(filename, "r"); - if (!fp) - fatal_error("fopen"); + if (!fp) { + fatal_error("Failed to read file from %s\n", filename); + } char* line = NULL; size_t line_capacity = 0; |