summaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authorcflip <cflip@cflip.net>2023-01-16 14:14:25 -0700
committercflip <cflip@cflip.net>2023-01-16 14:19:02 -0700
commit8be3915417bcafdbf2a8752980db96e06df096aa (patch)
treedc463de897bdc91220639809bef9082a7e5289a3
parent58d38d02b215f2e4829ccdc399df8d59bb6cb140 (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.
-rw-r--r--file.c11
1 files changed, 8 insertions, 3 deletions
diff --git a/file.c b/file.c
index 680f8ae..7604618 100644
--- a/file.c
+++ b/file.c
@@ -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;